Reputation: 3570
I have some ggplot code that worked fine in 0.8.9 but not in 0.9.1.
I am going to plot the data in theDF
and would like to plot a vertical line at xintercept="2010 Q1."
theGrid
is merely used to create theDF
.
theGrid <- expand.grid(2009:2011, 1:4)
theDF <- data.frame(YrQtr=sprintf("%s Q%s", theGrid$Var1, theGrid$Var2),
Minutes=c(1000, 2200, 1450, 1825, 1970, 1770, 1640, 1920, 1790, 1800, 1750, 1600))
The code used is:
g <- ggplot(theDF, aes(x=YrQtr, y=Minutes)) +
geom_point() +
opts(axis.text.x=theme_text(angle=90))
g + geom_vline(data=data.frame(Vert="2010 Q2"), aes(xintercept=Vert))
Again, this worked fine in R 2.13.2 with ggplot2 0.8.9, but does not in R 2.14+ with ggplot2 0.9.1.
A workaround is:
g + geom_vline(data=data.frame(Vert=4), aes(xintercept=Vert))
But that is not a good solution for my problem.
Maybe messing around with scale_x_discrete
might help?
Upvotes: 7
Views: 6950
Reputation: 762
You could try this:
g + geom_vline(aes(xintercept = which(levels(YrQtr) %in% '2010 Q1')))
This avoids the need to create a dummy data frame for the selected factor level. The which() command returns the index (or indices if the right side of the %in% operator is a vector) of the factor level[s] to associate with vlines.
One caution with this is that if some of the categories do not appear in your data and you use drop = TRUE
in the scale, then the lines will not show up in the right place.
Upvotes: 16
Reputation: 23758
When you use a character vector, or a factor, for the x-axis in a plot the default values given to each of the unique items is simply integer starting at 1. So, if your levels are c("A" "B", "C") then the x-axis locations are c(1,2,3). There is no such thing as a character location, just a character label. If you want a vertical line at A then put it at 1. If you want it half way in between A and B then put it 1.5. Again, those are the defaults. If a particular plot did something else you can easily work that out by putting lines at a few locations and seeing what happens.
Upvotes: 2