Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid overlapping x-axis labels in ggplot facet grid

Tags:

r

ggplot2

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.

like image 691
Jeremyjaytaylor Avatar asked Dec 19 '16 14:12

Jeremyjaytaylor


People also ask

How do you prevent X axis labels from overlapping each other in Ggplot?

To avoid overlapping labels in ggplot2, we use guide_axis() within scale_x_discrete().

How do you prevent X axis labels from overlapping each other?

0 A common problem in making plots, say a barplot or boxplot with a number of groups is that, names of the groups on x-axis label often overlap with each other. Till now, one of the solutions to avoid overlapping text x-axis is to swap x and y axis with coord_flip() and make a horizontal barplot or boxplot.

How do you prevent X axis labels from overlapping each other in Excel?

Stop Labels overlapping chartRight click on the Axis. Choose the Format Axis option. Open the Labels dropdown. For label position change it to 'Low'

How do I change x labels in R Ggplot?

To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .


1 Answers

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

like image 181
Valentin Avatar answered Oct 13 '22 17:10

Valentin