15
votes

I am trying to plot a facet grid of growth plots and my labels at the ends of each plot are overlapping with the each other. Here is sample code using the mpg data:

print(ggplot(data = aggregate(hwy~class+year, data=mpg, mean), aes(x = year, y=hwy))+
    geom_line(aes(group = 1))+
    geom_point()+
    facet_wrap(~class,  nrow = 2)+
    xlab("Year")+
    scale_x_discrete(limits=unique(mpg$year)))

How do I prevent this overlapping, perhaps by moving the tick marks and labels in from the edge of the plot. I tried using the margin within theme, but I did not have success with this either. Thank you for your help.

1
The easiest soln. is too increase the width of your graphics window or output device. Howvever, you could rotate the labels p + theme(axis.text.x = element_text(angle=-90, vjust=0.5)). Or you could add a little space using expand..scale_x_discrete(expand=c(0.5, 0.5), limits=unique(mpg$year))user20650

1 Answers

21
votes

I presume what you are after is adjusting the horizontal spacing between facet panels with panel.spacing.x in theme (tested with ggplot2_3.0.0).

ggplot(data = aggregate(hwy~class+year, data=mpg, mean), aes(x = year, y=hwy))+
  geom_line(aes(group = 1))+
  geom_point()+
  facet_wrap(~class,  nrow = 2)+
  xlab("Year")+
  scale_x_discrete(limits=unique(mpg$year)) +
  theme(panel.spacing.x = unit(4, "mm"))

Before

enter image description here

After - using panel.spacing.x()

enter image description here