首页 > 解决方案 > 将默认颜色集成到个性化主题 ggplot

问题描述

我创建了自己的主题,现在我还想标准化使用的颜色集。我尝试使用此提要中 Viktor 的回答中提供的列表解决方案来执行此操作:

将调色板与 ggplot2 主题相关联

df <- mtcars
uwvPalet <- c("#0078D2","#003282","#C4D600")
theme_uwv <- function(base_size = 22, base_family = "Verdana"){theme_hc(base_size = base_size, base_family = base_family)%+replace%theme(plot.title = element_text(color = rgb(0, 120, 210)), complete = TRUE)}
theme_uwv2 <- list(theme_uwv, scale_color_manual(values = uwvPalet))
ggplot(df, aes(fill = cyl, x = am, y = mpg)) + geom_bar(position = "dodge", stat="identity") + theme_uwv2()

不幸的是,我得到了错误:

Error in theme_uwv2() : could not find function "theme_uwv2"

有谁知道我该如何解决这个问题?

标签: ggplot2ggthemes

解决方案


以下对我有用。theme_uwv2需要从theme_uwv()列表元素返回的值,而不是函数本身。此外,您正在制作一个以 为主要颜色变量的图,因此出于演示目的fill,我已替换scale_color_manual()为。scale_fill_manual()

library(ggplot2)
library(ggthemes)

df <- mtcars
uwvPalet <- c("#0078D2","#003282","#C4D600")
theme_uwv <- function(base_size = 22, base_family = "Verdana"){
  theme_hc(base_size = base_size, base_family = base_family) %+replace% 
    theme(plot.title = element_text(color = rgb(0, 120, 210, maxColorValue = 255)), 
          complete = TRUE)}
theme_uwv2 <- list(theme_uwv(), scale_fill_manual(values = uwvPalet))

ggplot(df, aes(fill = as.factor(cyl), x = am, y = mpg)) + 
  geom_col(position = "dodge") + 
  ggtitle("test") +
  theme_uwv2

在此处输入图像描述


推荐阅读