I do different plots with ggplot2
and want them all to have the same colour. The thing is that I use different geom
s that sometimes work with fill
and sometimes with col
. See here:
df <- data.frame(x= 1:10, y= 1:10, col= c(1:5, 5:1))
library(ggplot2)
gg1 <- ggplot(df, aes(x, group= x, fill= col)) +
geom_bar()
gg2 <- ggplot(df, aes(x, y, col= col)) +
geom_point()
If I want both ggplot2
objects to have the same colour palette, say Spectral
, I would need to do gg1 + scale_fill_distiller(palette = "Spectral")
and gg2 + scale_colour_distiller(palette = "Spectral")
. Pay attention to the difference "scale_fill_distiller" and "scale_colour_distiller". If we mix this up, the plot changes.
I have many plots and do not instantly know whether a col
or fill
was used, i.e. I have to manually print the plot before I can actually add the palette. So the question is whether there is a generalized function which adds a colour palette to any col
, fill
, whatever easthetic. So the function is suppost for gg1
and gg2
like this: gg1 + scale_generalized_distiller(palette = "Spectral")
and gg2 + scale_generalized_distiller(palette = "Spectral")
What I do so far:
I simpy add all whats possible. Like this:
gg1 +
scale_colour_distiller(palette = "Spectral") +
scale_fill_distiller(palette = "Spectral")
gg2 +
scale_colour_distiller(palette = "Spectral") +
scale_fill_distiller(palette = "Spectral")
I hope there is a more elegant way.
>Solution :
You can use the aesthetics
parameter, either with scale_color_distiller
or scale_fill_distiller
:
gg1 +
scale_color_distiller(palette = "Spectral", aesthetics = c("colour", "fill"))
gg2 +
scale_color_distiller(palette = "Spectral", aesthetics = c("colour", "fill"))
Checks
ggFill1 <- gg1 +
scale_fill_distiller(palette = "Spectral", aesthetics = c("colour", "fill"))
ggColor1 <- gg1 +
scale_color_distiller(palette = "Spectral", aesthetics = c("colour", "fill"))
all.equal(ggFill1,ggColor1)
# [1] TRUE
ggFill2 <- gg2 +
scale_fill_distiller(palette = "Spectral", aesthetics = c("colour", "fill"))
ggColor2 <- gg2 +
scale_color_distiller(palette = "Spectral", aesthetics = c("colour", "fill"))
all.equal(ggFill2,ggColor2)
# [1] TRUE