6

I would like to add minor gridlines to categorical data on plot produced with ggplot2. For example,

library("ggplot2")
data<-data.frame(xcategory=rep(c("a","b","c"),each=30), yvalue=c(1,3,6))

ggplot(data,aes(x=xcategory,y=yvalue,alpha=1.0,size=5))+
                geom_point(position=position_jitter(width=0.1,height=0.0))+
                theme_bw()+
                scale_x_discrete(name="Categorical Data") +
                scale_y_continuous(name="Continuous Response",limits=c(0,7)) +
                theme(axis.text.x=element_text(angle = 90),legend.position="none")

Produces the following graph:

What I don't want

But what I would like is for the categorical gridlines to bound the category name so that I can jitter all of the data within the gridlines. Here's an example from paint where I made edits in red:

What I want

The red lines bounding "b" are probably all that I need, I was just trying to illustrate three columns of equal width.

Help or direction to a similar question that I missed is greatly appreciated. I have tried adding grid information through "theme" with no success.

Docuemada
  • 1,519
  • 2
  • 17
  • 37

1 Answers1

9

You can use geom_vline() to add lines to plot and use numbers like 0.5, 1.5 to set positions. Numbers are vectors that starts with 0.5 and goes by 1 till "number of categories" +0.5. Those lines will be between categories names.

ggplot(data,aes(x=xcategory,y=yvalue,alpha=1.0,size=5))+
  geom_vline(xintercept=c(0.5,1.5,2.5,3.5),color="red")+
  geom_point(position=position_jitter(width=0.1,height=0.0))+
  theme_bw()+
  scale_x_discrete(name="Categorical Data") +
  scale_y_continuous(name="Continuous Response",limits=c(0,7)) +
  theme(axis.text.x=element_text(angle = 90),legend.position="none")

enter image description here

Didzis Elferts
  • 84,813
  • 12
  • 241
  • 189
  • This works for the simple example that I provided. If I had a varying number of categories, I suppose that I could create a new xintercept vector with a simple function. Thanks. +1 – Docuemada May 15 '13 at 16:29
  • @Docuemada Yes, just create vector of values that starts with 0.5 and ends with "number of categories"+0.5 – Didzis Elferts May 15 '13 at 16:31
  • this is my more generic fix: `+ geom_vline(xintercept=seq(1,length(mydata[,1]),2)+.5,color="red")` – ErichBSchulz Nov 15 '14 at 14:11