Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
I can never remember how to rotate the x-axis labels with ggplot2: theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
# Adapted from https://stackoverflow.com/a/7267364/1036500 by Andrie de Vries
# This is it: theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
library(ggplot2)
td <- expand.grid(
hjust=c(0, 0.5, 1),
vjust=c(0, 0.5, 1),
angle=c(0, 45, 90),
text="text"
)
td$angle_exp <-
with(td,
ifelse(angle == 0, "angle = 0",
ifelse(angle == 45, "angle = 45",
"angle = 90")))
,
ggplot(td, aes(x=hjust,
y=vjust)) +
geom_point(colour = "red",
size = 5) +
geom_text(aes(label=text,
angle=angle,
hjust=hjust,
vjust=vjust),
size = 5) +
facet_grid(~angle_exp) +
scale_x_continuous(breaks=c(0, 0.5, 1),
expand=c(0, 0.2)) +
scale_y_continuous(breaks=c(0, 0.5, 1),
expand=c(0, 0.2)) +
theme_minimal(base_size = 18) +
ggtitle("To rotate x-axis label text 90 degrees we use:\ntheme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))")
@benmarwick

This comment has been minimized.

Copy link
Owner Author

@benmarwick benmarwick commented Mar 7, 2018

image

@ChrisBeeley

This comment has been minimized.

Copy link

@ChrisBeeley ChrisBeeley commented Nov 6, 2018

Ha! Me neither! Thanks for this, it's a real time saver

@centeio

This comment has been minimized.

Copy link

@centeio centeio commented Jan 10, 2019

Thanks!! So useful.

@Maddocent

This comment has been minimized.

Copy link

@Maddocent Maddocent commented Mar 3, 2019

I look this up on Google, maybe once a week ;-), thanks for the help!

@prerit912

This comment has been minimized.

Copy link

@prerit912 prerit912 commented Mar 27, 2019

I think it's because the names are not so intuitive. ( I also in the group, can't remember it, I can try to by heart it) :P

@briglo

This comment has been minimized.

Copy link

@briglo briglo commented Jul 4, 2019

as a github newb, i am proud to give you my first star :) thanks for this

@joelnitta

This comment has been minimized.

Copy link

@joelnitta joelnitta commented Aug 3, 2019

I visit this probably once a week. best.gist.ever.

@SAbhaya

This comment has been minimized.

Copy link

@SAbhaya SAbhaya commented Aug 8, 2019

Thanks.

@maggiesuero

This comment has been minimized.

Copy link

@maggiesuero maggiesuero commented Jun 11, 2020

I guess this gist never gets old. It's great!!! Thank you very much

@idot

This comment has been minimized.

Copy link

@idot idot commented Jan 26, 2021

There is an alternative since 3.3.0: stackoverflow

guides(x=guide_axis(angle = 90))

the h/v-just are set automatically sensibly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment