【问题标题】:Setting ggplot margins automatically to include geom_text自动设置 ggplot 边距以包含 geom_text
【发布时间】:2020-04-01 11:41:22
【问题描述】:

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

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")

为了将“aaaaaaaaaaa”保留在情节中,我可以手动更改情节边距,将“c(1, 1, 1, 1)”替换为“c(1, 3, 1, 1)”。

但是有没有办法自动设置边距,以便“aaaaaaaaaa”出现在情节中?

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

【问题讨论】:

  • 你能举个例子吗?
  • @RuiBarradas,我添加了一个示例。你能想出一些办法吗?
  • 你检查过this question吗?

标签: r ggplot2


【解决方案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")

【讨论】:

  • 看起来“向内”参数确实在图中移动了标签。但是有没有办法让标签保持在点的右侧并让边距自动调整?不过谢谢你的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 2012-06-19
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多