将调色板与ggplot2主题相关联

Sam*_*rke 13 r ggplot2

我希望我的ggplot2主题使用一组特定的颜色,但是看不到如何避免主题之外的单独一行.

我有这些数据:

library(ggplot2)
mycars <- mtcars
mycars$cyl <- as.factor(mycars$cyl)
Run Code Online (Sandbox Code Playgroud)

这是我绘制的虚拟主题:

mytheme <- theme(panel.grid.major = element_line(size = 2))

ggplot(mycars, aes(x = wt, y = mpg)) +
  geom_point(aes(color = cyl)) +
  mytheme
Run Code Online (Sandbox Code Playgroud)

没有自定义颜色

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

mycolors <- c("deeppink", "chartreuse", "midnightblue")
Run Code Online (Sandbox Code Playgroud)

我可以以某种方式将其添加到我的ggplot2主题,以便我不会在最后重复这些额外的代码行:

ggplot(mycars, aes(x = wt, y = mpg)) +
  geom_point(aes(color = cyl)) +
  mytheme +
  scale_color_manual(values = mycolors)
Run Code Online (Sandbox Code Playgroud)

与颜色

我试过了:

mytheme2 <- mytheme + scale_color_manual(values = mycolors)
Run Code Online (Sandbox Code Playgroud)

但得到了:

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

Vic*_*orp 9

您好,您可以将自定义元素放在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
Run Code Online (Sandbox Code Playgroud)


bap*_*ste 7

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

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)) )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

palette(c("deeppink", "chartreuse", "midnightblue"))
p
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

palette(RColorBrewer::brewer.pal(5, "Set1"))
p
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述