【问题标题】:R 'cowplot' neatly produce gridded plot with shared (common) legends and unique legendsR'cowplot' 巧妙地生成具有共享(通用)图例和独特图例的网格图
【发布时间】:2017-10-20 10:32:44
【问题描述】:

查看我的相关问题和接受的答案here

我正在尝试生成一个类似于已接受答案中的图,即网格图具有共享的公共图例和附加到网格上每个图的不同的唯一图例。

具体来说,我想要一个 3 行 1 列的网格,每行有 1 个绘图。像这样:

使用以下代码生成:

  library (ggplot2)
  library(gridExtra)
  library (grid)
  library(cowplot)


   diamonds2 <- diamonds[sample(nrow(diamonds), 500), ]

   # 3 ggplot plot objects with multiple legends 1 common legend and 3 unique legends

  p1<- ggplot(diamonds2, aes(x=price, y= depth, color= clarity , shape= cut )) +
geom_point(size=5) + labs (shape = "unique legend", color = "common legend")

  p2 <- ggplot(diamonds2, aes(x=price, y= depth, color= clarity , shape=   color )) +
geom_point(size=5) + labs (shape = "unique legend", color = "common legend")

  p3 <- ggplot(diamonds2, aes(x=price, y= depth, color= clarity , shape= clarity )) +
geom_point(size=5) + labs (shape = "unique legend", color = "common legend")

  cowplot::plot_grid(
  cowplot::plot_grid(
  p1 + scale_color_discrete(guide = FALSE),
  p2 + scale_color_discrete(guide = FALSE),
  p3 + scale_color_discrete(guide = FALSE),
  nrow=3, ncol = 1))

但有一个与每个绘图对象的color = 参数相关的共享图例。

我已经尝试了以下代码的许多变体,并在咨询cowplot 文档后添加/调整/删除了各种参数/参数,但我无法获得像上面那样的整洁图,底部有共享图例(或任何有用的地方!) - 我尝试过的所有东西都会返回一个拥挤的情节,如下所示。

修改上述代码以包含共享图例:

  cowplot::plot_grid(
   cowplot::plot_grid(
    p1 + scale_color_discrete(guide = FALSE),
    p2 + scale_color_discrete(guide = FALSE),
    p3 + scale_color_discrete(guide = FALSE),
    nrow=3, ncol = 1
   ),
   cowplot::get_legend(p1 + scale_shape(guide = FALSE) +   theme(legend.position = "bottom")), nrow=3)

这会导致这样一个拥挤的情节,有很多空白:

谁能建议我哪里出错了?

【问题讨论】:

    标签: r plot ggplot2 grid-layout cowplot


    【解决方案1】:

    每次调用plot_grid 都会分割您的绘图区域。在这里,您嵌套了两个对plot_grid 的调用,每个调用3 行。 cowplot 因此将绘图区域分成两等份:

    • 在顶部,它放置了您的散点图
    • 在底部,您的图例占据第一行,底部两行没有任何内容,在压缩散点图时会产生大量空白。

    您可以指定每个绘图区域的相对高度,从而为散点图提供更多空间,并为底部的图例提供更少空间。例如 85% 的地块和 15% 的图例:

    cowplot::plot_grid(
       cowplot::plot_grid(
        p1 + scale_color_discrete(guide = FALSE),
        p2 + scale_color_discrete(guide = FALSE),
        p3 + scale_color_discrete(guide = FALSE),
        ncol = 1, align = "v"
       ),
       cowplot::get_legend(p1 + scale_shape(guide = FALSE) + 
          theme(legend.position = "bottom")),
       ncol=1, rel_heights=c(.85, .15))
    

    产生:

    【讨论】:

    • 啊 - 现在很明显了。解释的很清楚,谢谢。我已经编辑了你的答案以包含结果图,希望你不介意。
    猜你喜欢
    • 2016-09-17
    • 1970-01-01
    • 2018-05-04
    • 2014-07-07
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多