Reputation: 3441
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.
Upvotes: 4
Views: 9928
Reputation: 94307
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.
Upvotes: 3
Reputation: 13827
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)
Upvotes: 5