ggplot和ggarrange -如何防止图例框被切断?

35g0bw71  于 2023-01-28  发布在  其他
关注(0)|答案(2)|浏览(138)

对我来说,这个问题只发生在Mac上。不幸的是,我正在旅行,我只带了我的MacBook。这里是一个最小的例子。问题不会出现在个别地块,但只有当他们通过ggarrange连接。

library(ggplot2)
library(ggpubr)

p1 <- ggplot(mtcars, aes(x = mpg, y = disp, color = as.factor(am))) +
  geom_point() +
  theme(legend.box.background = element_rect(color = "black", size = 1))

p2 <- ggplot(mtcars, aes(x = hp, y = disp, color = as.factor(am))) +
  geom_point() +
  theme(legend.box.background = element_rect(color = "black", size = 1))

ggarrange(p1, p2, common.legend = T, legend = "right")

现在看一下图表:

正如你所看到的,图例框的右边框被切掉了。我怎样才能防止它这样做呢?

zpf6vheq

zpf6vheq1#

如果您想坚持使用ggpubr,这里有一个解决方案,无可否认不是很好,但很有效。

library(ggplot2)
library(ggpubr)

p1 <- ggplot(mtcars, aes(x = mpg, y = disp, color = as.factor(am))) +
  geom_point() +
  theme(legend.box.background = element_rect(color = "white", linewidth  = 1),
        legend.background = element_rect(color = "black", linewidth  = 1),
        legend.box.margin = margin(r = 20))

p2 <- ggplot(mtcars, aes(x = hp, y = disp, color = as.factor(am))) +
  geom_point() +
  theme(legend.box.background = element_rect(color = "white", linewidth  = 1),
        legend.background = element_rect(color = "black", linewidth  = 1),
        legend.box.margin = margin(r = 20))

ggarrange(p1, p2, common.legend = T, legend = "right")

2hh7jdfx

2hh7jdfx2#

一个选项是切换到patchwork以将图粘合在一起:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars, aes(x = mpg, y = disp, color = as.factor(am))) +
  geom_point()

p2 <- ggplot(mtcars, aes(x = hp, y = disp, color = as.factor(am))) +
  geom_point()

p1 + p2 +
  plot_layout(guides = "collect") &
  theme(legend.box.background = element_rect(color = "black", size = 1))

相关问题