在ggplot2中将geom_text与geom_vline对齐 [英] Align geom_text to a geom_vline in ggplot2

查看:240
本文介绍了在ggplot2中将geom_text与geom_vline对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用vjust作为解决方法,并详细说明了 通过尝试和错误获得可接受的距离.但这有时很耗时,并且需要更改 字体大小和轴比例.

I used vjust as workaround and elaborate an acceptable distance by try and error. But this is sometimes very time consuming and changes with the font size and the axis scale.

在示例中自动对齐文本是否有更好的方法?

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.5.

Another solution for the case of one line labels would be to add a line break before/after and keep the default 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))

这篇关于在ggplot2中将geom_text与geom_vline对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆