Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate the axis labels in ggplot2?

Tags:

r

ggplot2

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

I had finalPlot as the ggplot object. To add labels I used

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

How can I change the orientation of the y axis label to make it appear horizontal and if possible span it across two lines like

Number of
Solutions
like image 565
Ankit Avatar asked Apr 08 '12 14:04

Ankit


People also ask

How to rotate x-axis text labels in ggplot2?

We can rotate axis text labels using theme() function in ggplot2. To rotate x-axis text labels, we use “axis.text.x” as argument to theme() function. And we specify “element_text(angle = 90)” to rotate the x-axis text by an angle 90 degree.

How to set axis labels to a vertical angle in R?

If we want to set our axis labels to a vertical angle, we can use the theme & element_text functions of the ggplot2 package. We simply have to add the last line of the following R code to our example plot: Figure 2: Barchart with 90 Degree Angle.

How to avoid overlapping label texts in ggplot2?

In most cases we can use coord_flip () to switch and and y-axis and make the axis text easy to read. And with g gplot2 version 3.3.0, we can avoid overlapping label texts by moving the labels along y-axis alternatively.

What is the difference between the angle and vjust in ggplot2?

The angle controls the angle of the text while vjust and hjust control the vertical and horizontal justification of the text. The following step-by-step example shows how to use this syntax in practice. library(ggplot2) #create bar plot ggplot (data=df, aes(x=team, y=points)) + geom_bar (stat="identity")


1 Answers

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

Error: Use 'theme' instead. (Defunct; last used in version 0.9.1)

These days you should use

finalPlot + ylab("Number of\nSolutions") + theme(axis.title.y = element_text(angle=0))
like image 107
Jeff Hammerbacher Avatar answered Sep 18 '22 15:09

Jeff Hammerbacher