﻿ 在r中组合两个图 - 代码日志

#### 在r中组合两个图

``````# plot 1 , heatmap plot
set.seed (123)
myd <- data.frame ( matrix(sample (c(1, 0, -1), 500, replace = "T"), 50))

mmat <-  cor(myd)
diag(mmat) <- NA
mmat[upper.tri (mmat)] <- NA
heatmap (mmat, keep.dendro = F, Rowv = NA, Colv = NA)
``````

``````  vard <- data.frame ( position = c(1, 10, 15, 18, 20, 23, 24, 30, 35, 40),
Names =paste ("X", 1:10, sep = ""))
plot(vard\$position, vard\$position - vard\$position,
type = "n", axes = FALSE, xlab = "", ylab = NULL, yaxt = "n")
polygon(c(0, max(vard\$position + 0.08 * max(vard\$position)),
max(vard\$position) + 0.08 * max(vard\$position),
0), 0.2 * c(-0.3, -0.3, 0.3, 0.3), col = "green4")
segments(vard\$position, -0.3, vard\$position,                0.3)
text(vard\$position, 0.7, vard\$position,
srt = 90)
text(vard\$position, -0.7, vard\$Names)
``````

``````library(grid)

## Data: heatmap
set.seed (123)
myd <- data.frame ( matrix(sample (c(1, 0, -1), 500, replace = "T"), 50))
mmat <-  cor(myd)
diag(mmat) <- NA
mmat[upper.tri (mmat)] <- NA
## Data: Positions
vard <- c(1, 10, 15, 18, 20, 23, 24, 30, 35, 40)

## Construct a function to convert a numeric matrix to a matrix of color names.
## The lowest value in the matrix maps to red, the highest to white,
## and the NAs to "transparent".
convertToColors <- function(mat) {
# Produce 'normalized' version of matrix, with values ranging from 0 to 1
rng <- range(mat, na.rm = TRUE)
m <- (mat - rng[1])/diff(rng)
# Convert to a matrix of sRGB color strings
m2 <- m; class(m2) <- "character"
m2[!is.na(m2)] <- rgb(colorRamp(heat.colors(10))(m[!is.na(m)]), max = 255)
m2[is.na(m2)] <- "transparent"
return(m2)
}

## Initialize plot and prepare two viewports
grid.newpage()
heatmapViewport <- viewport(height=1/sqrt(2), width=1/sqrt(2), angle = -135)
annotationViewport <- viewport(y = 0.7, height = 0.4)

## Plot heat map
pushViewport(heatmapViewport)
grid.raster(t(convertToColors(mmat)), interpolate = FALSE)
upViewport()

## Precompute x-locations of text and segment elements
n <- nrow(mmat)
v_x <- vard/max(vard)
X_x <- seq(0, 1, len=n)

## Plot the annotated green bar and line segments
pushViewport(annotationViewport)
## Green rectangle
grid.polygon(x = c(0,0,1,1,0), y = c(.45,.55,.55,.45,.45),
gp = gpar(fill = "green4"))
pushViewport(viewport(width = (n-1)/n))
## Segments and text marking vard values
grid.segments(x0 = v_x, x1 = v_x, y0 = 0.3, y1 = 0.7)
grid.text(label = vard, x = v_x, y = 0.75, rot = 90)
## Text marking heatmap column names (X1-X10)
grid.text(paste0("X", seq_along(X_x)), x = X_x, y=0.05,
gp = gpar(fontface="bold"))
## Angled lines
grid.segments(x0 = v_x, x1 = X_x, y0 = 0.29, y1 = 0.09)
upViewport()
upViewport()
``````