【问题标题】:Common legend and identical plot width for multi-panel plot多面板绘图的通用图例和相同的绘图宽度
【发布时间】:2014-11-28 22:46:09
【问题描述】:

我想知道是否有一种方法可以同时为多面板绘图提供相同的绘图宽度和。我知道如何在没有图例或没有垂直居中的图例的情况下获得相同的绘图宽度。

这是我用于常见图例 (https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs) 的 Hadley 修复:

library(ggplot2)
library(gridExtra)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ] 

p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(carat, price, data=dsamp, colour=clarity, geom="path")

g_legend<-function(p){
tmp <- ggplotGrob(p)
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}

legend <- g_legend(p1)
lwidth <- sum(legend$width)

## using grid.arrange for convenience
## could also manually push viewports
grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
                                    p2 + theme(legend.position="none"),
                                    main ="this is a title",
                                    left = "This is my global Y-axis title"), legend, 
                 widths=unit.c(unit(1, "npc") - lwidth, lwidth), nrow=1)

为了说明我的观点,我更改了p2,添加了同一数据集的另外两个变量,以保持与常见图例相同的清晰度:

p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(depth, table, data=dsamp, colour=clarity, geom="path")

g_legend<-function(p){
tmp <- ggplotGrob(p)
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}

legend <- g_legend(p1)
lwidth <- sum(legend$width)

## using grid.arrange for convenience
## could also manually push viewports
grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
                                    p2 + theme(legend.position="none"),
                                    main ="this is a title",
                                    left = "This is my global Y-axis title"), legend, 
                 widths=unit.c(unit(1, "npc") - lwidth, lwidth), nrow=1)

这在本例中可能没有意义,但我在同一个实验单元上有四个不同的测量值,我想以图形方式显示在 2 个具有相同绘图宽度和一个共同的垂直居中图例的绘图中。

【问题讨论】:

    标签: r layout ggplot2


    【解决方案1】:

    我认为你可以通过 faceting 更好地实现你的目标:

    ggplot(dsamp, aes(x = carat, y = price, colour = clarity)) +
      geom_point(data = cbind(dsamp, group = 1)) +
      geom_path(data = cbind(dsamp, group = 2)) +
      facet_grid(group ~ .) +
      theme(strip.text.y = element_blank(),
            strip.background = element_blank()) +
      ggtitle("this is a title")
    

    我假设您的图中的变量与示例中的变量相同。否则,当我需要自己对齐绘图时,我不得不进行大量修改:例如,请参阅 scatterplot with alpha transparent histograms in R。

    【讨论】:

    • 不,我没有相同的变量,所以这不起作用。我编辑了上面的帖子以提供更多详细信息。不过感谢您的链接!
    猜你喜欢
    • 1970-01-01
    • 2022-01-15
    • 2019-02-22
    • 2011-10-14
    • 2010-11-19
    • 2015-09-11
    • 2016-10-04
    • 2017-08-11
    • 2021-12-28
    相关资源
    最近更新 更多