简体   繁体   English

创建 ggplot 主题:自定义 colors 用于可变级别

[英]Creating ggplot theme: custom colors for variable levels

I'm trying to create a new theme in ggplot2 for plotting political parties for my country, I want to set the color for some and other like random_party_1 y random_party_2 set a random color.我正在尝试在 ggplot2 中创建一个新主题来为我的国家绘制政党,我想为一些和其他一些设置颜色,比如 random_party_1 y random_party_2 设置一个随机颜色。

data <- data.frame(party = c('FA','PN', 'random_party1','random_party2', 'FA','PN', 'random_party1','random_party2'), 
                   year = c(2010, 2010, 2010, 2010, 2008, 2008, 2008, 2008), 
                   value = c(50, 20, 30, 10, 50, 50, NA, NA), 
                   color = c('#013197','#B0C2D3','assign_random_color1','assign_random_color2','#013197','#B0C2D3','assign_random_color','assign_random_color'))

Then I want to use this as a fill or color argument but I don't know how to implement it without declaring it manually like because it's going to depend on the data of each year:然后我想将其用作填充或颜色参数,但我不知道如何在不手动声明的情况下实现它,因为它将取决于每年的数据:

cols <- c("FA" = "#013197", "PN" = "#B0C2D3", "random_party1" = "assign_random_color1", "random_party2" = "assign_random_color2")
p + scale_colour_manual(values = cols)

I think the best way to achieve this is via a custom function:我认为实现这一点的最佳方法是通过自定义 function:

colorize <- function(vec)
{
  levs <- if(is.factor(vec)) levels(vec) else levels(factor(vec))
  predefined <- c("FA", "PN")
  pal <- c('#013197','#B0C2D3')
  pal <- pal[match(levs, predefined)]
  blanks <- which(is.na(pal))
  pal[blanks] <- sample(colours(100), length(blanks))
  pal
}

So suppose we set up your plot like this:因此,假设我们像这样设置您的 plot:

p <- ggplot(data, aes(factor(year), value, fill = party)) + geom_col(position = "dodge")

Then we can run our code once to get fixed colors for the predefined parties and random colors for the unassigned parties:然后我们可以运行我们的代码一次,为预定义的各方获取固定的 colors,为未分配的各方获取随机的 colors:

p + scale_fill_manual(values =  colorize(data$party))

在此处输入图像描述

And we can see only the random parties' colors change if we run exactly the same code again:如果我们再次运行完全相同的代码,我们只能看到随机方的 colors 发生变化:

p + scale_fill_manual(values =  colorize(data$party))

在此处输入图像描述

Created on 2020-06-11 by the reprex package (v0.3.0)reprex package (v0.3.0) 于 2020 年 6 月 11 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM