使用cowplot将共享图例对齐到绘图网格中心

5
可在cowplot包的教程中找到可重现的示例。 https://cran.r-project.org/web/packages/cowplot/vignettes/shared_legends.html 复制示例代码:
library(ggplot2)
library(cowplot)
#down-sampled diamonds data set
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]

# Make three plots.
# We set left and right margins to 0 to remove unnecessary spacing in the
# final plot arrangement.
p1 <- qplot(carat, price, data=dsamp, colour=clarity) +
  theme(plot.margin = unit(c(6,0,6,0), "pt"))
p2 <- qplot(depth, price, data=dsamp, colour=clarity) +
  theme(plot.margin = unit(c(6,0,6,0), "pt")) + ylab("")
p3 <- qplot(color, price, data=dsamp, colour=clarity) +
  theme(plot.margin = unit(c(6,0,6,0), "pt")) + ylab("")

# arrange the three plots in a single row
prow <- plot_grid( p1 + theme(legend.position="none"),
           p2 + theme(legend.position="none"),
           p3 + theme(legend.position="none"),
           align = 'vh',
           labels = c("A", "B", "C"),
           hjust = -1,
           nrow = 1
           )
legend_b <- get_legend(p1 + theme(legend.position="bottom"))

# add the legend underneath the row we made earlier. Give it 10% of the height
# of one plot (via rel_heights).
p <- plot_grid( prow, legend_b, ncol = 1, rel_heights = c(1, .2))
p

这个示例展示了一个图表,其中图例被绘制在网格的左下角。然而,以前它是不同的,因为图例是绘制在图表的底部中心的。这里是几个月前我个人代码生成的一个示例。 https://s1.postimg.org/8pf2en1zen/Untitled.png (上传工具目前对我无效)
在任何包的未知更改之后重新运行我的旧代码会将图例绘制到左下角(如教程中所示,从上面数第三个图)。 https://s1.postimg.org/3agjw7n9gf/Untitled2.png 问题是如何调整代码以绘制图例并使其与底部居中。
1个回答

16

您可以通过以下方式设置legend_b:

legend_b <- get_legend(p1 + theme(legend.position=c(0.3,0.8),legend.direction = "horizontal"))

更好的方式:

legend_b <- get_legend(p1 + theme(legend.direction = "horizontal",legend.justification="center" ,legend.box.just = "bottom"))

谢谢。我猜其他图例大小需要进行“试错”。 - nouse
legend_b <- get_legend(p1 + theme(legend.position="none",legend.direction = "horizontal")) 这对我也有效。 - Zeinab Ghaffarnasab
在 get_legend(p1 + theme(legend.position = "none", legend.direction = "horizontal")) 中出现错误:图必须包含一个图例。 - nouse
3
请尝试以下代码:legend_b <- get_legend(p1 + theme(legend.direction = "horizontal",legend.justification="center",legend.box.just = "bottom")) - Zeinab Ghaffarnasab
这看起来不错。你可能想要更新你的答案。 - nouse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接