Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2 wrap long x-axis labels over multiple rows

Tags:

r

ggplot2

I have a bar chart (I used ggplot2, geom_bar), but the labels for x-axis are too long and overlap. I would like to keep them as long as they are, but I also would like them to be horizontally (not vertically, nor with an angle). Is there some way to wrap the long labels over multiple (at least two) rows?

like image 433
Fanny Avatar asked Oct 19 '12 21:10

Fanny


People also ask

How to wrap axis labels of a ggplot2 plot in R?

The following R programming code demonstrates how to wrap the axis labels of a ggplot2 plot so that they have a maximum width. For this, we first have to install and load the stringr package. Now, we can use the str_wrap function of the stringr package to auto wrap the labels of our data to a certain width.

How to display x axis labels on several lines in R?

It can be handy to display X axis labels on several lines. For instance, to add the number of values present in each box of a boxplot. Change the names of your categories using the names () function. Increase the distance between the labels and the X axis with the mgp argument of the par () function. It avoids overlap with the axis.

What are long axis text labels in Excel?

A long axis text labels make harder to understand the plot and ofter it overlaps with the neighboring labels and obscuring the labels. Here we will see two different ways to wrap long axis labels into multiple ways.

How to change axis labels in a graph?

The functions which are used to change axis labels are : xlab ( ) : For the horizontal axis. ylab ( ) : For the vertical axis. labs ( ) : For both the axes simultaneously.


1 Answers

I am not aware of a way through ggplot directly. However you can do something like this:

ggplot(data.frame(x=1:10, y=1:10), aes(x,y)) +
  geom_point() +
  labs(x='really long label \n with a return')

With your axis labels to make them wrap at a length you choose.

like image 125
Justin Avatar answered Nov 10 '22 18:11

Justin