Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align axis label on the right with ggplot2

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))

plot with poorly aligned labels

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?

like image 552
Remi.b Avatar asked May 27 '16 16:05

Remi.b


People also ask

How do you stop axis labels overlapping in Ggplot?

To avoid overlapping labels in ggplot2, we use guide_axis() within scale_x_discrete().

How do I move the Y axis title in ggplot2?

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.

How do I change the position of an axis label in R?

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.

How do I make my axis labels bigger in ggplot2?

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.


2 Answers

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))

enter image description here

like image 114
Mike H. Avatar answered Oct 05 '22 13:10

Mike H.


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()

Plot

like image 39
JasonAizkalns Avatar answered Oct 05 '22 13:10

JasonAizkalns