This happens a lot to draw a ggplot with multiple aesthetic all referring to one variable. Then, to change the common legend title, the simple way I know is to do it for all common aesthetics using labs()
or guides()
.
For example
ggplot(data = mtcars, aes(x = mpg, y = wt,
color = factor(am), shape= factor(am), linetype=factor(am), fill=factor(am))) +
geom_point() + geom_smooth() +
labs(color="long legend title", shape="long legend title", linetype="long legend title", fill="long legend title")
is there any way not to repeat "long legend title"
for all common aesthetics in the code?
You could create a list of guide_legends and splice it with !!! to use it in the guides() function:
This might work for you:
library(ggplot2)
library(purrr)
aesthetics <- c("colour", "shape", "linetype", "fill")
# Guides provided to `guides()` must be named.
names(aesthetics) <- aesthetics
guide_legends <- map(aesthetics, ~ guide_legend("long legend title"))
ggplot(data = mtcars,
aes(x = mpg, y = wt,
color = factor(am),
shape= factor(am),
linetype=factor(am),
fill=factor(am))) +
geom_point() +
geom_smooth() +
guides(!!!guide_legends)