Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2: Labelling a horizontal line on the y axis with a numeric value

Tags:

r

ggplot2

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)) 

Thank you for your help.

like image 990
adam.888 Avatar asked Oct 13 '12 20:10

adam.888


People also ask

How do I add a horizontal line in ggplot2?

Example: To add the horizontal line on the plot, we simply add geom_hline() function to ggplot2() function and pass the yintercept, which basically has a location on the Y axis, where we actually want to create a vertical line.

How do I add a vertical line in ggplot2?

To create a vertical line using ggplot2, we can use geom_vline function of ggplot2 package and if we want to have a wide vertical line with different color then lwd and colour argument will be used. The lwd argument will increase the width of the line and obviously colour argument will change the color.


1 Answers

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))) 

enter image description here

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)) 

enter image description here

like image 102
Chase Avatar answered Sep 20 '22 23:09

Chase