将调色板与ggplot2主题相关联

时间:2016-04-07 12:51:06

标签: r 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)

但得到了:

  

错误:不知道如何添加scale_color_manual(values = mycolors)   主题对象

2 个答案:

答案 0 :(得分:7)

您好,您可以将自定义元素放在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

答案 1 :(得分:6)

我有时会使用这个小技巧来改变绘图之间的调色板,

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

相关问题