Home > database >  How do I move my axis labels to the side in ggplot in R
How do I move my axis labels to the side in ggplot in R

Time:01-05

I want to set the x-axis label under the right corner of the plot, and the y-axis label to the left upper corner.

As an example of a plot, I made up this short piece of code:

#library(ggplot2)
library(titanic)
data("titanic_train", package = "titanic")
titanic <- titanic_train

ggplot(data = titanic, aes(x = Fare))   
  geom_histogram()  
 xlab("Want this on right side")

What I tried and what I want I found something that moves the whole y-axis to the right (scale_y_continuous(position = "right")) but not the x-label. I also found how to move the numbers on the labels plot with axis labels both centered

CodePudding user response:

This could be achieved by aligning the axis title to the right using theme(axis.title = element_text(hjust = 1)) (or axis.title.x and axis.title.y):

library(ggplot2)
library(titanic)
data("titanic_train", package = "titanic")
titanic <- titanic_train

ggplot(data = titanic, aes(x = Fare))  
  geom_histogram()  
  xlab("Want this on right side")  
  theme(axis.title = element_text(hjust = 1))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

  • Related