I have the following graph that I generated using ggplot2
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
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.
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.
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.
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")
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With