将geom_text与ggplot2中的geom_vline对齐

Jon*_*ein 22 r ggplot2

我使用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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Ros*_*tev 27

对于一行标签的另一种解决方案是在之前/之后添加换行符并保持默认值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))
Run Code Online (Sandbox Code Playgroud)

  • 另外,为了避免渲染多个副本,应该使用`annotate`而不是`geom_text`,请参阅/sf/ask/766698271/ -text生产逐GEOM的文本 (5认同)