【问题标题】:Add Legend to Multiple Figure in R将图例添加到 R 中的多个图形
【发布时间】:2013-06-07 18:58:48
【问题描述】:

我将多个图连接成一个图(具体为 24 个),我不太清楚如何为整个图添加图例。

par(mfrow = c(4,6))

for(i in 1:24){
x <- rep(0,3)
y <- rnorm(3, 3)
par(family = "Garamond")
col_vec <- c( "darkblue", "gray65", "maroon4")
plot(x,y, xaxt = 'n', xlab = '', ylab = '', xaxt='n', bty = "n",  ylim = c((min(y) - 1.5),(max(y) + 1.5)),  col = col_vec, pch = 19, cex =.8)
abline(h=y[2], lty=2, col = "gray89")}

title("Effect Size", outer = TRUE, line = -2, cex = 2)  
legend("topleft", c("Treatment 1", "Control", "Treatment 2"), col = col_vec, pch = 15)

如果有人知道如何将图例添加到左侧而不是每个图或所有图,那就太好了;请注意,如果没有 legend 命令,上面的代码会生成下图:

【问题讨论】:

  • 您可以在初始布局中腾出空间,使用plot.new() 设置新的绘图区域,并在其中添加legend()
  • 也就是说,lattice 或 ggplot2 会使整个过程变得微不足道

标签: r plot legend par


【解决方案1】:

对于基本图形,我建议使用layout 而不是par(mfrow=c(4,6))。这样您就可以为自己留出额外的空间来放置图例,使用plot.new() 移动到最后一个面板区域并将图例放置在那里。

【讨论】:

    【解决方案2】:

    这里有一个关于 ggplot2 的建议

    library(plyr)
    xy <- rdply(24, data.frame(x=0, y=rnorm(3,3), id=1:3))
    
    library(ggplot2)
    
    ggplot(xy, aes(x, y, colour=factor(id))) + 
      facet_wrap(~.n, scales="free", ncol=4) +
      geom_point() + 
      annotate("segment", x=-0.1, xend=-0.1, y=-Inf, yend=+Inf) +
      scale_x_continuous(breaks=NULL, expand=c(0,0), lim=c(-0.1, 0.1)) +
      scale_y_continuous(expand=c(0,0.1)) +
      theme_minimal() + 
      theme(strip.text.x = element_blank(),
            axis.title.x = element_blank(),
            axis.title.y = element_blank()) +
      scale_colour_manual("", labels=c("Treatment 1", "Control", "Treatment 2"),
                          values=c( "darkblue", "gray65", "maroon4"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 2011-11-30
      相关资源
      最近更新 更多