Reputation: 23054
I want my ggplot2 theme to use a specific set of colors, but don't see how to avoid a separate line outside of the theme.
I have this data:
library(ggplot2)
mycars <- mtcars
mycars$cyl <- as.factor(mycars$cyl)
And here's a dummy theme I plot with:
mytheme <- theme(panel.grid.major = element_line(size = 2))
ggplot(mycars, aes(x = wt, y = mpg)) +
geom_point(aes(color = cyl)) +
mytheme
I want the point colors to default to my custom palette:
mycolors <- c("deeppink", "chartreuse", "midnightblue")
Can I somehow add that to my ggplot2 theme so that I don't constantly repeat this extra line of code at the end:
ggplot(mycars, aes(x = wt, y = mpg)) +
geom_point(aes(color = cyl)) +
mytheme +
scale_color_manual(values = mycolors)
I tried:
mytheme2 <- mytheme + scale_color_manual(values = mycolors)
But got:
Error: Don't know how to add scale_color_manual(values = mycolors) to a theme object
Upvotes: 21
Views: 7133
Reputation: 77124
I sometimes use this little trick to change colour palettes between plots,
library(ggplot2)
mycars <- mtcars
mycars$cyl <- as.factor(mycars$cyl)
scale_colour_discrete <- function(...) scale_colour_manual(values=palette())
(p <- ggplot(mycars, aes(x = wt, y = mpg)) +
geom_point(aes(color = cyl)) )
palette(c("deeppink", "chartreuse", "midnightblue"))
p
palette(RColorBrewer::brewer.pal(5, "Set1"))
p
Upvotes: 10
Reputation: 13866
Hi you can put your custom element in a list
:
# Data
library("ggplot2")
mycars <- mtcars
mycars$cyl <- as.factor(mycars$cyl)
# Custom theme
mytheme <- theme(panel.grid.major = element_line(size = 2))
mycolors <- c("deeppink", "chartreuse", "midnightblue")
# put the elements in a list
mytheme2 <- list(mytheme, scale_color_manual(values = mycolors))
# plot
ggplot(mycars, aes(x = wt, y = mpg)) +
geom_point(aes(color = cyl)) +
mytheme2
Upvotes: 17