将ggplot2图放置在网格中并具有1个图例

时间:2014-03-20 19:15:34

标签: r ggplot2

我有以下代码生成k=2类的图表列表。

library(ggplot2)
library(cumplyr)
library(scales)
library(reshape2)
library(RColorBrewer)
library(tools)
library(gridExtra)

jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan","#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000"))
myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))

x   = 1:50
y   = 1:50
pts = cartesian_product(c('x','y'))


make_df <- function(i) {
    k = if(i <= 5) 1 else 2
    d1 = cbind(pts, runif(nrow(pts),min=0,max=10*i), 1)
    colnames(d1) = c("x","y","val", "k")
    return(d1)
}

dflist = lapply(as.list(1:10),make_df)


make_plot <- function(data, gmin = 0, gmax = 100) {
    p1 <- ggplot(data)
    p1 <- p1 + geom_tile(aes(x = x, y = y, fill = val))
    p1 <- p1 + scale_fill_gradientn(colours = myPalette(gmax), limits=c(gmin,gmax))
    return(p1)
}

plotlist = lapply(dflist, make_plot)
g = do.call(arrangeGrob, plotlist)

我在最后安排情节时遇到了麻烦。这些图可以是k = 1类型或类型k = 2.我想:

  • 将地块排列成2 x 5格,
  • 只有1个传奇
  • 使用适当的k值
  • 标记每一行图
  • 沿着行引用的图表彼此接近,可能只是每个
  • 之间的一个小间隙

我一直在用我的车轮旋转几个小时无济于事!

谢谢!

2 个答案:

答案 0 :(得分:2)

这就是我对facet_wrap所做的事情(在这种情况下网格没有意义):

ggplot(df, aes(x=x, y=y, fill=val)) + 
  geom_tile() + 
  scale_fill_gradientn(colours = myPalette(100), limits=c(0,100)) +
  facet_wrap(~ k, nrow=2) +
  theme(axis.text.x=element_text(angle=90))

产地:

enter image description here

我不得不稍微修改你的代码:

make_df <- function(i) {
  k = if(i <= 5) 1 else 2
  d1 = cbind(pts, runif(nrow(pts),min=0,max=10*i), i)  # I think you want the last value to be `i`, but I'm guessing
  colnames(d1) = c("x","y","val", "k")
  return(d1)
}
pts = expand.grid(x, y)  # cartesian_product() didn't work for me, but I think this is equivalent
dflist = lapply(as.list(1:10),make_df)
df <- do.call(rbind, dflist)

答案 1 :(得分:1)

如果列意味着什么,你可以做这样的事情

library(ggplot2)

nplot = 10

# assume that the first 5 are of the same group, and last 5 are of the same group
dlist = lapply(1:10, function(i){
    x = rnorm(100)
    y = rnorm(100)
    p = i*(i<=5)+(i-5)*(i>5)
    k = 1*(i<=5)+2*(i>5)
    data.frame(x,y,p,k)
})

# create a large dataframe
D = do.call(rbind, dlist)
ggplot(D, aes(x=x,y=y)) + geom_point() + facet_grid(k~p) 

ggplot