自动设置ggplot页边距以包括geom_text

时间:2020-04-01 11:41:22

标签: r ggplot2

假设我使用以下代码绘制了以下图:

plot

data = data.frame(x = 1:5, y = 1:5)
ggplot(data, aes(x = x, y = y)) + 
  geom_point() +
  geom_text(x = 5, y = 5, label = "aaaaaaaaaaaaaaa", hjust = 0) +
  theme_classic() + 
  theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
  coord_cartesian(clip = "off")

要在绘图中保留“ aaaaaaaaaaaaa”,我可以手动更改绘图边距,将“ c(1,1,1,1)”替换为“ c(1,3,1,1)”。 / p>

但是有没有一种方法可以自动设置边距,以使“ aaaaaaaaa”位于图中?

例如,如果“ aaaaaaaa ...”的长度改为100个字符,我将不得不再次更改页边距。我想知道是否可以通过某种方式编写代码/使用程序包,以使打印边距自动调整为始终包含所有geom_text对象。

1 个答案:

答案 0 :(得分:1)

This question seems to be answered already,其中ggplot2vjusthjust添加了新选项。您可以简单地使用"inward"来确保您的文本不会被剪切:

data = data.frame(x = 1:5, y = 1:5)
ggplot(data, aes(x = x, y = y)) + 
  geom_point() +
  geom_text(x = 5, y = 5, label = "aaaaaaaaaaaaaaa", hjust = 0) +
  theme_classic() + 
  theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
  coord_cartesian(clip = "off")

enter image description here