ggplot2
ShortcutsThis package allows easy access to some common ggplot2
tasks.
library(ggplot2)
library(patchwork)
library(labelled)
library(ggeasy)
Rotating the x
axis labels is a very frequently looked up task, and we can make it easier. If we create a simple ggplot2
plot
<- ggplot(mtcars, aes(hp, mpg)) + geom_point() p
then by default, this looks like
+ labs(title = "ggplot2 default") p
We can perform various rotations though
<- p +
p1 easy_rotate_x_labels() +
labs(title = "default rotation")
<- p +
p2 easy_rotate_x_labels(angle = 45, side = "right") +
labs(title = "angle = 45")
<- p +
p3 easy_rotate_x_labels("startattop") +
labs(title = "text starts at top")
<- p +
p4 easy_rotate_x_labels("startatbottom") +
labs(title = "text starts at bottom")
+ p2) / (p3 + p4) (p1
Removing legends is made easier by the easy_remove_legend
function. When called without arguments, all legends are removed (equivalent to theme(legend.position = "none")
). Alternatively, the names of aesthetics for which legends should be removed can be passed.
<- ggplot(mtcars, aes(wt, mpg, colour = cyl, size = hp)) +
p geom_point()
<- p +
p1 labs(title = "With all legends")
<- p +
p2 easy_remove_legend() +
labs(title = "Remove all legends")
<- p +
p3 easy_remove_legend(size) +
labs(title = "Remove size legend")
<- p +
p4 easy_remove_legend(size, color) +
labs(title = "Remove both legends specifically")
+ p2) / (p3 + p4) (p1
Changing plot labels to a specified string isn’t particularly difficult (labs(x = "my label")
) but wouldn’t it be even nicer if you could just add labels to your data.frame
columns (e.g. using labelled::var_labels()
) and have these reflected in your plot. easy_labs()
makes this possible.
## create a copy of the iris data
<- iris
iris_labs
## add labels to the columns
<- c('Sepal Length', 'Sepal Width', 'Petal Length', 'Petal Width', 'Flower\nSpecies')
lbl var_label(iris_labs) <- split(lbl, names(iris_labs))
These are visible if you use View(iris_labs)
in RStudio
<- ggplot(iris_labs, aes(x = Sepal.Length, y = Sepal.Width)) +
p geom_line(aes(colour = Species))
<- p + labs(title = "default labels")
p1 <- p +
p2 easy_labs() +
labs(title = "Replace titles with column labels")
<- p +
p3 easy_labs(x = 'My x axis') +
labs(title = "Manually add x axis label")
<- iris_labs
iris_labs_2 var_label(iris_labs_2$Species) <- "Sub-genera"
<- p + geom_point(data = iris_labs_2, aes(fill = Species), shape = 24) +
p4 easy_labs() +
labs(title = "Additional labels can be added in other aesthetics")
+ p2) / (p3 + p4) (p1
easy_labs also extends to facetting
+ geom_point(data = iris_labs_2, aes(fill = Species), shape = 24) +
p4 facet_wrap(~Species) +
easy_labs() +
labs(title = "Facetting works")