Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding vertical line to ggplot bar plot

Tags:

r

ggplot2

I am trying to add vertical lines to a ggplot that displays count data per month. My x-axis is month as a factor, but my vertical lines represent Julian days.

For example, with these data:

dat <- structure(list(Month = structure(1:12, .Label = c("Jan", "Feb", 
"Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", 
"Dec"), class = c("ordered", "factor")), Data = c(1, 1, 2, 2, 
6, 11, 19, 23, 19, 13, 5, 1)), .Names = c("Month", "Data"), class = "data.frame", row.names = c(NA, 
-12L))

I can make the following bar plot

ggplot(dat)+ geom_bar(aes(x=  Month, y = Data), stat="identity")

How can I then add two vertical lines with the x-intercept of Julian day 68 and 252 using geom_vline?

I am not sure how to plot the lines which reference a continuous scale on the monthly (factor) x-axis data.

like image 231
B. Davis Avatar asked Oct 25 '25 15:10

B. Davis


1 Answers

When your x axis is a factor, then geom_vline will use the order of appearance of each value as its intercept.

You then just need to identify what fraction would correspond to the exact dates you're looking for. In this example, I'm using two illustrative fractions.

ggplot(dat)+ geom_bar(aes(x=  Month, y = Data), stat="identity") + 
geom_vline(xintercept = 5.2) +
  geom_vline(xintercept = 8.7) 
like image 62
rafa.pereira Avatar answered Oct 27 '25 04:10

rafa.pereira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!