Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 here but I want the axis name to move from centered to right.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want something like this:
plot with axis labels both centered

>Solution :

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`.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading