【问题标题】:Common legend for multiple plots in RR中多个图的常见图例
【发布时间】:2012-05-10 12:34:00
【问题描述】:

我正在使用 R 和 Latex 一起绘制一些情节,并试图为所有情节制作一个共同的图例。

我在同一页面上有六个单独的图。我在 R 中分别制作了每个图,然后在 Latex 中使用 \includegraphics 将它们显示在同一页面上。

每个图表都有相同的图例信息,因此我不想在每个图中都有一个图例,我希望在页面底部显示一个水平图例。不幸的是,我无法弄清楚如何在没有情节的情况下制作传奇。一旦有了单独的图例图像,我就会知道如何使用 Latex 将其包含在页面底部。

我试图用来制作图例的代码是

plot(1, type = "n", axes=FALSE, xlab="", ylab="")
plot_colors <- c("blue","black", "green", "orange", "pink")

legend(.6,1.3,legend = c("Fabricated Metal", "Iron and Steel", "Paper", 
"Beverages", "Tobacco"), 
       col=plot_colors, lwd=5, cex=.5, horiz = TRUE)

但是,字体太小,图例框的边被剪掉了。

【问题讨论】:

  • 如果所有绘图都使用基本 R 函数,您可能更容易使用 layout 将它们全部放在 R 中的一个绘图中。

标签: r legend


【解决方案1】:

仅使用par 修改代码以对齐底部的图例。

   n <- 6
   par(oma = c(4,1,1,1), mfrow = c(2, 3), mar = c(2, 2, 1, 1))
   for (i in 1:n){
      plot(runif(5),runif(5),xlab = '',ylab = '')
   }
   par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0), new = TRUE)
   plot(0, 0, type = 'l', bty = 'n', xaxt = 'n', yaxt = 'n')
   legend('bottom',legend = c("Fabricated Metal", "Iron and Steel", "Paper", "Beverages", "Tobacco"), col = c("blue","black", "green", "orange", "pink"), lwd = 5, xpd = TRUE, horiz = TRUE, cex = 1, seg.len=1, bty = 'n')
   # xpd = TRUE makes the legend plot to the figure

【讨论】:

    【解决方案2】:

    我所说的一个简单例子:

    m <- matrix(c(1,2,3,4,5,6,7,7,7),nrow = 3,ncol = 3,byrow = TRUE)
    
    layout(mat = m,heights = c(0.4,0.4,0.2))
    
    for (i in 1:6){
        par(mar = c(2,2,1,1))
        plot(runif(5),runif(5),xlab = "",ylab = "")
    }
    
    
    plot(1, type = "n", axes=FALSE, xlab="", ylab="")
    plot_colors <- c("blue","black", "green", "orange", "pink")
    legend(x = "top",inset = 0,
            legend = c("Fabricated Metal", "Iron and Steel", "Paper","Beverages", "Tobacco"), 
            col=plot_colors, lwd=5, cex=.5, horiz = TRUE)
    

    【讨论】:

    • 您可能需要在添加图例之前添加par(mar=c(0,0,0,0)) 或以其他方式重置边距
    【解决方案3】:

    试试这个,

    plot_colors <- c("blue","black", "green", "orange", "pink")
    text <- c("Fabricated Metal", "Iron and Steel", "Paper", 
    "Beverages", "Tobacco")
    plot.new()
    par(xpd=TRUE)
    legend("center",legend = text, text.width = max(sapply(text, strwidth)),
           col=plot_colors, lwd=5, cex=1, horiz = TRUE)
    par(xpd=FALSE)
    

    【讨论】:

    • 上面的代码创建了一个太大的图例 - 你只能看到它的中心,边被切掉。即使我导出文件并重新打开它,我也没有完整的图例。
    • 这取决于您的字体大小和设备宽度。你可能想看看lattice 可以产生的图例,它们在间隔不同的键方面可能更聪明一些。 (您需要使用gridBase 在基础图中添加图例)。
    猜你喜欢
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2013-06-12
    • 2018-03-31
    • 2019-01-11
    • 2018-04-09
    • 2021-10-01
    • 1970-01-01
    相关资源
    最近更新 更多