2016-04-07 24 views
7

我想让我的ggplot2主题使用特定的一组颜色,但没有看到如何避免主题之外的单独线条。将调色板与ggplot2主题相关联

我有这样的数据:

library(ggplot2) 
mycars <- mtcars 
mycars$cyl <- as.factor(mycars$cyl) 

,这里是一个虚拟的主题,我与情节:

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

我想点颜色默认为我的自定义调色板:

mycolors <- c("deeppink", "chartreuse", "midnightblue") 

我可以以某种方式添加到我的GGPLOT2主题,让我不要总是在最后重复的代码,这额外的行:

ggplot(mycars, aes(x = wt, y = mpg)) + 
    geom_point(aes(color = cyl)) + 
    mytheme + 
    scale_color_manual(values = mycolors) 

with colors

我想:

mytheme2 <- mytheme + scale_color_manual(values = mycolors) 

但得到了:

Error: Don't know how to add scale_color_manual(values = mycolors) to a theme object

回答

5

嗨,你可以把你的自定义元素在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 
+0

看起来像这样不会导致问题,当我在不适用'scale_color_manual'的图表上使用此主题时。我正在为其他颜色的场景添加它,并且它似乎工作正常,例如'mytheme2 < - list(mytheme,scale_color_manual(values = mycolors),scale_fill_manual(values = mycolors))'以涵盖填充和色彩美学。 –

4

我有时用这个小动作来改变地块之间调色板,

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))) 

enter image description here

palette(c("deeppink", "chartreuse", "midnightblue")) 
p 

enter image description here

palette(RColorBrewer::brewer.pal(5, "Set1")) 
p 

enter image description here