Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

r - Associate a color palette with ggplot2 theme

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

without custom colors

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)

with colors

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...