繁体   English   中英

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

[英]ggplot and ggarrange - how to prevent legend box from being cut off?

对我来说,这个问题只发生在 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")

现在看图表:

在此处输入图像描述

如您所见,图例框的右边框被切掉了。 我如何防止它这样做?

如果你想坚持使用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")

在此处输入图像描述

一种选择是切换到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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM