Consider the following
d = data.frame(y=rnorm(120),
x=rep(c("bar", "long category name", "foo"), each=40))
ggplot(d,aes(x=x,y=y)) +
geom_boxplot() +
theme(axis.text.x=element_text(size=15, angle=90))
The x-axis labels are aligned by the center of the label. Is it possible to automatically align on the right so that every label would end right below the graph?
To avoid overlapping labels in ggplot2, we use guide_axis() within scale_x_discrete().
For this purpose, we can use theme function of ggplot2 package. We would need to use the argument of theme function as axis. title. y=element_text(angle=0)) and this will write the Y-axis title to horizontal but the position will be changed to top.
Key ggplot2 R functionsp + xlab(“New X axis label”): Change the X axis label. p + ylab(“New Y axis label”): Change the Y axis label. p + labs(x = “New X axis label”, y = “New Y axis label”): Change both x and y axis labels.
To increase the X-axis labels font size using ggplot2, we can use axis. text. x argument of theme function where we can define the text size for axis element. This might be required when we want viewers to critically examine the X-axis labels and especially in situations when we change the scale for X-axis.
This is precisely what the hjust
and vjust
parameters are for in ggplot
. They control the horizontal and vertical justification respectively and range from 0 to 1. See this question for more details on justifications and their values (What do hjust and vjust do when making a plot using ggplot?).
To get the labels the way you want you can use:
hjust = 0.95
(to leave some space between the labels and the axis)vjust = 0.2
(to center them in this case)ggplot(d,aes(x=x,y=y)) + geom_boxplot() +
theme(axis.text.x=element_text(size=15, angle=90,hjust=0.95,vjust=0.2))
Alternatively, flip the axis, your customers will thank you and have less neck pain (plus, I find most boxplots easier to interpret with this orientation):
ggplot(d, aes(x = x, y = y)) +
geom_boxplot() +
coord_flip()
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