Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot facetted geom_boxplot: reduce space between x-axis categories

Tags:

r

ggplot2

boxplot

I am creating a boxplot using ggplot. When I reduce the width of the boxplot the space between the x-axis categories increases. I would like to be able to reduce the space between the x-axis categories and bring the box plots closer to each other.

p<-ggplot(data.plot1, aes(time2, Count))
p+geom_boxplot(outlier.shape = NA, width=0.3)+
  ggtitle("")+ylab("Cell Count (cells/mL) ")+ xlab("Time")  + 
  theme_bw()+  coord_cartesian(ylim = c(0, 850))+
  geom_hline(data=normal1, aes(yintercept = val), linetype="dashed")+
  facet_grid(.~CellType1)

enter image description here

So, basically, reduce the space between Day 0, Day30, Day 100 and bring the boxplots closer to each other.

like image 700
user3089803 Avatar asked Nov 10 '22 08:11

user3089803


1 Answers

As mentioned in the comments, narrowing the graphics device is one way of doing it. Another way to do it without changing the size of the graphics device is to add spaces between your bars and the sides of the panels. Note: Since your question is not reproducible, I have used the build-in infert dataset, which serves demonstrative purposes. Assuming that this is your original facetted side-by-side boxplots:

p<-ggplot(infert, aes(as.factor(education), stratum))
p+geom_boxplot(outlier.shape = NA, width=0.3)+
  ggtitle("")+ylab("Cell Count (cells/mL) ")+ xlab("Time")  + 
  theme_bw()+  coord_cartesian(ylim = c(0, 80))+
  # geom_hline(data=normal1, aes(yintercept = val), linetype="dashed")+
  facet_grid(.~induced)

enter image description here

This brings the categories together by adding white space on both ends of each panel:

p+geom_boxplot(outlier.shape = NA, width=0.6)+
  ggtitle("")+ylab("Cell Count (cells/mL) ")+ xlab("Time")  + 
  theme_bw()+  coord_cartesian(ylim = c(0, 80))+
  # geom_hline(data=normal1, aes(yintercept = val), linetype="dashed")+
  facet_grid(.~induced) +
  scale_x_discrete(expand=c(0.8,0))

enter image description here

The two numbers in scale_x_discrete(expand=c(0.8,0)) indicate the multiplicative and additive expansion constant that "places some distance away from the axes". See ?scale_x_discrete. This effectively "squishes" the boxplots in each panel together, which also reduces the width of each boxplot. To compensate for that, I increased the width to width=0.6 in geom_boxplot. Notice that the x-axis labels are now overlapping. You will have to experiment with different expansion factors and width sizes to get exactly how you want it.

Also see this question for a related issue: Remove space between bars within a grid

like image 192
acylam Avatar answered Nov 15 '22 05:11

acylam