【问题标题】:Placing ggplot2 plots in a grid and having 1 legend将 ggplot2 图放在网格中并具有 1 个图例
【发布时间】:2014-03-20 19:15:34
【问题描述】:

我有以下代码生成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 值标记每一行图
  • 让沿行引号的图彼此靠近,也许每个图之间只有一个小间隙

我已经用这个旋转了几个小时,但无济于事!

谢谢!

【问题讨论】:

  • 您不使用facet_grid 是否有特定原因?听起来就像它会产生你想要的一样。
  • BrodieG,具体原因是我对它的存在一无所知:)。感谢您的参考。
  • 如果你因为某些原因不想使用facet_grid,可以从this answer得到一些启发

标签: r ggplot2


【解决方案1】:

这就是我对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))

生产:

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

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,6 2,7 3,8 等是否相关。如果列代表某些东西,您可能需要考虑facet_grid(k~p),例如5 个街区,2 次治疗。
【解决方案2】:

如果列有意义,你可以这样做

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) 

【讨论】:

    猜你喜欢
    • 2013-01-28
    • 2020-05-06
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多