假设我使用以下代码绘制了以下图:
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对象。
答案 0 :(得分:1)
This question seems to be answered already,其中ggplot2
为vjust
和hjust
添加了新选项。您可以简单地使用"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")