How to rotate axis labels in ggplot2?

I have the following graph that I generated using ggplot2 enter image description here

I had finalPlot as a ggplot object. To add shortcuts, I used

 finalPlot + stat_bin() + scale_x_continuous('Solution Cost') + scale_y_continuous('Number of Solutions')` 

How to change the orientation of the y-axis label so that it looks horizontal and, if possible, spans it along two lines, for example,

 Number of Solutions 
+7
source share
2 answers

For the angle of rotation of the axis text, you need to use element_text() . See this post on SO for some examples. For the spacing between two lines, I would add "\n" to the place in the line where you want to place the new line.

This will set the correct orientation for the y axis text and cause a line break:

 finalPlot + ylab("Number of\nSolutions") + theme(axis.title.y = element_text(angle = 0)) 
+5
source

The syntax has changed in recent versions of ggplot2; if you try the answer above you will get

Error: Use the theme instead. (Defunct; the latter is used in version 0.9.1)

These days you should use

 finalPlot + ylab("Number of\nSolutions") + theme(axis.title.y = element_text(angle=0)) 
+13
source

All Articles