在ggplot2中将geom_text与geom_vline对齐

44

我使用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似乎能够实现它们应该实现的功能,而超出这个范围的值总是更加偏心。 - baptiste
1
我希望计算机查找字体大小并将文本框放置在正确的距离,这样用户就不必调整vjust值。 - Jonas Stein
1
我认为自动定位标签即使图表始终是简单的,也会很难。你看过directlabels包吗? - SlowLearner
我认为directlabels朝着正确的方向发展。但是我没有找到像上面示例中注释线条的方法。 - Jonas Stein
2个回答

48

当标签只有一行时,另一个解决方案是在上下添加换行符,并保持默认值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))

简单而有效。我喜欢这个! - fdetsch
9
为了避免生成多个副本,应该使用“annotate”而不是“geom_text”,详见https://dev59.com/3Wgu5IYBdhLWcg3w9bn_ - Valentas
@Valentas 如果 annotate 能够更好地完成同样的任务,那么更新答案以使用它将是很好的选择。 - stevec

2
另一个选项是使用伟大的geomtextpath包中的geom_textvline函数。这实际上可以结合geom_textgeom_vline函数。该包有一些创建曲线,直线自动文本注释的创造性函数。请查看此link以获取更多示例。以下是一个可重现的示例:
library(ggplot2)
library(geomtextpath)
# Using geom_textvline
ggplot(data=mtcars, aes(x=hp, y=mpg)) +
  geom_point() +
  geom_textvline(label = "the strong cars", xintercept = 200, vjust = 1.3) +
  geom_textvline(label="the weak cars", xintercept = 200, vjust = -0.7) +
  theme_bw()

# Using geom_textabline with slope
ggplot(data=mtcars, aes(x=hp, y=mpg)) +
  geom_point() +
  geom_textabline(slope = 0.05, label = "the strong cars", intercept = 10, vjust = 1.3) +
  geom_textabline(slope = 0.05, label="the weak cars", intercept = 10, vjust = -0.7) +
  theme_bw()

创建于2022年8月25日,使用reprex v2.0.2

在这个特定的例子中(由OP设置),这将绘制两条线,一条在另一条上方,这可能会产生有趣但并不总是期望的效果。 - tjebo
然而更重要的是,它不会消除这个问题所涉及的不必要的手动vjust。 - tjebo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接