Home Articles

将调色板与ggplot2主题相关联

Asked
Viewed 102 times
8

我希望我的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 Answers

  • 6

    嗨,您可以将自定义元素放在_1839562中:

    # 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
    
  • 5

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

    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

Related