Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gridlines between discrete values

Tags:

r

ggplot2

When using a discrete values ggplot2 provides a gridline at the tick value at the centre of the value

library(reshape2)

ggplot(data=tips, aes(x=time, y=total_bill, fill=sex)) +
    geom_bar(stat="identity", position=position_dodge())

enter image description here

How can I set the grid line from the x axis to appear between the discrete values (i.e. between 'Dinner' and 'Lunch')

I have tried to set panel.grid.minor.x however (I think) as it is discrete this does not work ... this is not a minor value for it to plot the girdline on.

ggplot(data=tips, aes(x=time, y=total_bill, fill=sex)) +
    geom_bar(stat="identity", position=position_dodge()) + 
    theme(panel.grid.minor.x = element_line())
like image 695
Christopher Hackett Avatar asked Jun 07 '14 16:06

Christopher Hackett


1 Answers

You can add a vertical line that will act as a grid line as follows:

geom_vline(xintercept=1.5, colour='white')

You can, of course, alter line width, colour, style, etc. as needed, and add multiple lines in the appropriate locations if you have several groups of bars that need to be separated by grid lines. For example, using some fake data:

set.seed(1)
dat = data.frame(total_bill=rnorm(100,80,10), 
                 sex=rep(c("Male","Female"),50),
                 time=sample(c("Breakfast","Brunch","Lunch","Afternoon Tea","Dinner"), 
                             100, replace=TRUE))
dat$time = factor(dat$time, 
                  levels=c("Breakfast","Brunch","Lunch","Afternoon Tea","Dinner"),
                  ordered=TRUE)

ggplot(data=dat, aes(x=time, y=total_bill, fill=sex)) +
  geom_bar(stat="identity", position=position_dodge()) +
  geom_vline(xintercept=seq(1.5, length(unique(dat$time))-0.5, 1), 
             lwd=1, colour="black")

enter image description here

like image 112
eipi10 Avatar answered Oct 18 '22 15:10

eipi10