R ggplot2:用数值标记 y 轴上的水平线 [英] R ggplot2: Labelling a horizontal line on the y axis with a numeric value

查看:32
本文介绍了R ggplot2:用数值标记 y 轴上的水平线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ggplot 中有一条水平线,我想在 y 轴上标记它的值 (7.1).

I have a horizontal line in a ggplot and I would like to label it's value (7.1) on the y axis.

library(ggplot2)
df <- data.frame(y=c(1:10),x=c(1:10))
h <- 7.1
plot1 <- ggplot(df, aes(x=x,y=y)) + geom_point() 
plot2 <- plot1+ geom_hline(aes(yintercept=h))

感谢您的帮助.

推荐答案

不清楚您是否希望 7.1 成为 y 轴的一部分,或者您是否只是想要一种标记线的方法.假设是前者,您可以使用 scale_y_continuous() 来定义自己的中断.像这样的事情可能会做你想做的事(很可能需要一些摆弄):

It's not clear if you want 7.1 to be part of the y-axis, or if you just want a way to label the line. Assuming the former, you can use scale_y_continuous() to define your own breaks. Something like this may do what you want (will need some fiddling most likely):

plot1+ geom_hline(aes(yintercept=h)) + 
  scale_y_continuous(breaks = sort(c(seq(min(df$y), max(df$y), length.out=5), h)))

假设是后者,这可能是您更想要的:

Assuming the latter, this is probably more what you want:

plot1 + geom_hline(aes(yintercept=h)) +
  geom_text(aes(0,h,label = h, vjust = -1))

这篇关于R ggplot2:用数值标记 y 轴上的水平线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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