简体   繁体   中英

adding vertical line to ggplot bar plot

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.

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) 

The data is plotted with a single unit per month, so you need to add the line as a fraction of the year in months, with some offset for the bar size:

ggplot(dat) +
  geom_bar(aes(x = Month, y = Data), stat = "identity") + 
  geom_vline(xintercept = 12 * (c(68, 252) / 365) + 0.5) 

Check this by looking at the lines for day 1 and day 365:

ggplot(dat) +
  geom_bar(aes(x = Month, y = Data), stat = "identity") + 
  geom_vline(xintercept = 12 * (c(1, 365) / 365) + 0.5) 

every other day will be linearly interpolated across the graph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM