【问题标题】:Align geom_text to a geom_vline in ggplot2将 geom_text 与 ggplot2 中的 geom_vline 对齐
【发布时间】:2013-08-06 22:39:03
【问题描述】:

我使用vjust 作为解决方法并详细说明 通过尝试和错误可接受的距离。但这有时非常耗时并且会发生变化 字体大小和轴比例。

有没有更好的方法来自动对齐示例中的文本?

library(ggplot2)

ggplot(data=mtcars, aes(x=hp, y=mpg))+
geom_point()+
theme_bw() +
  geom_vline(xintercept=200, colour="grey") +
  geom_text(aes(x=200, label="the strong cars", y=20), colour="blue", angle=90, vjust = 1.2, text=element_text(size=11))+
  geom_text(aes(x=200, label="the weak cars", y=20), colour="red", angle=90, vjust = -1, text=element_text(size=11))

ggsave(filename="geomline.png", width=5.5, height=2*3, dpi=300)

【问题讨论】:

  • 您希望对齐方式如何? vjust=0 和 vjust=1 似乎在做他们应该做的事情,超出这个范围的值总是更偏心。
  • 我希望计算机查看字体大小并将文本框放置在正确的距离。因此,用户不必玩弄 vjust 值。
  • 我认为自动定位标签会很困难,即使情节总是很简单。你看过directlabels 包吗?
  • 我认为 directlabels 的方向是正确的。但是我发现没有办法像上面的例子那样注释行。

标签: r ggplot2


【解决方案1】:

对于单行标签的另一种解决方案是在之前/之后添加换行符并保持默认的 vjust=0.5。

ggplot(data=mtcars, aes(x=hp, y=mpg)) +
  geom_point() +
  theme_bw() +
  geom_vline(xintercept=200, colour="grey") +
  geom_text(aes(x=200, label="\nthe strong cars", y=20), colour="blue", angle=90, text=element_text(size=11)) +
  geom_text(aes(x=200, label="the weak cars\n", y=20), colour="red", angle=90, text=element_text(size=11))

【讨论】:

  • 简单有效。我喜欢!
  • 另外,为避免渲染多个副本,应使用annotate 而不是geom_text,参见stackoverflow.com/questions/10952832/…
  • @Valentas 如果annotate 做同样的事情但更好,最好更新答案以使用它
猜你喜欢
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 2021-01-06
  • 2017-11-25
  • 1970-01-01
  • 2022-11-25
  • 2016-09-26
  • 1970-01-01
相关资源
最近更新 更多