3

我正在使用该包垂直patchwork组合多个ggplot2图。无论比例名称的长度如何,我都希望每个地块的比例直接在另一个上方。目前,这些天平并没有相互对齐。

我愿意使用ggpubr,或者facet_grid()他们是否可以使用,但我已经看到 facets不允许多个 scales,我还没有找到任何使用的解决方案ggpubr

library(ggplot2)
library(patchwork)

set.seed(0)
testdata <- data.frame(x=1:10, y=1:10, col=runif(10))

g1 <- ggplot(testdata, aes(x=x,y=y,col=col)) + geom_point() + 
  scale_color_gradient(name="Short")
g2 <- ggplot(testdata, aes(x=x,y=y,col=col)) + geom_point() + 
  scale_color_gradient(name="A rather longer name")
g1/g2

ggsave("testfile.tiff", units = "mm", device="tiff", 
       width=100, height=100, dpi = 100)

比例未对齐的示例图

理想输出:

比例对齐的示例图

4

2 回答 2

4

有了plot_layout你可以“收集”传说。这用作默认值theme(legend.position = 'right')& theme(legend.position = 'right')如果要更改图例的位置,可以在 plot_layout 之后添加并调整位置。

g1/g2 + plot_layout(guides = 'collect') # & theme(legend.position = 'right') <- adjust position here!

ggsave("testfile.tiff", units = "mm", device="tiff", 
       width=100, height=100, dpi = 100)  

在此处输入图像描述

于 2021-02-12T15:39:14.843 回答
3

我也很想知道可以解决此问题的拼凑参数,但我认为没有(如果我错了,请纠正我)。您可能已经注意到,Hadley 的答案已有 10 多年的历史,从那时起人们一直在研究 ggplot2。该ggnewscale软件包解决了每个地块有多个比例的问题。这是一种使用多色标的分面方法:

library(ggplot2)
library(ggnewscale)

set.seed(0)
testdata <- data.frame(x=1:10, y=1:10, col=runif(10))

ggplot(mapping = aes(x = x, y, y)) +
  geom_point(data = transform(testdata, 
                              facet = factor("Top", c("Top", "Bottom"))),
             aes(colour = col)) +
  scale_colour_continuous(name = "Short") +
  new_scale_colour() +
  geom_point(data = transform(testdata,
                              facet = factor("Bottom", c("Top", "Bottom"))),
             aes(colour = col)) +
  scale_colour_continuous(name = "A rather longer name") +
  facet_wrap(~ facet, ncol = 1)

于 2021-02-12T15:30:22.060 回答