Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

geom_vline with Character xintercept

Tags:

plot

r

ggplot2

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?

like image 517
Jared Avatar asked Jun 19 '12 01:06

Jared


1 Answers

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.

like image 188
Dennis Avatar answered Sep 24 '22 04:09

Dennis