首页 > 解决方案 > ggplot2 - 面积图中的两个颜色系列

问题描述

我有一个关于 R 中 ggplot2 的边缘案例的问题。

他们不喜欢你添加多个图例,但我认为这是一个有效的用例。

我有一个包含以下变量的大型经济数据集。

year = year of observation
input_type = *labor* or *supply chain*
input_desc = specific type of labor (eg. plumbers OR building supplies respectively)
value = percentage of industry spending

我正在制作一张大约 15 年的面积图。有 39 种不同的输入描述,所以我希望用户在两个主要颜色括号(比如绿色和蓝色)中看到两个主要组成部分(内部员工支出或外包/供应支出),但 ggplot 不会让我分组我的颜色就是这样。

这是我尝试过的几件事。

垃圾代码重现

spec_trend_pie<- data.frame("year"=c(2006,2006,2006,2006,2007,2007,2007,2007,2008,2008,2008,2008),
           "input_type" = c("labor", "labor", "supply", "supply", "labor", "labor","supply","supply","labor","labor","supply","supply"),
           "input_desc" = c("plumber" ,"manager", "pipe", "truck", "plumber" ,"manager", "pipe", "truck", "plumber" ,"manager", "pipe", "truck"), 
           "value" = c(1,2,3,4,4,3,2,1,1,2,3,4))
spec_broad <- ggplot(data = spec_trend_pie, aes(y = value, x = year, group = input_type, fill = input_desc)) + geom_area()

这给了我

Error in f(...) : Aesthetics can not vary with a ribbon

然后我尝试了这个

sff4 <- ggplot() + 
  geom_area(data=subset(spec_trend_pie, input_type="labor"), aes(y=value, x=variable, group=input_type, fill= input_desc)) +
  geom_area(data=subset(spec_trend_pie, input_type="supply_chain"), aes(y=value, x=variable, group=input_type, fill= input_desc)) 

这给了我这个形象......如此接近......但不完全在那里。 在此处输入图像描述

为了让您了解所需的内容,这是我很久以前在 GoogleSheets 中能够做的一个示例。 在此处输入图像描述

标签: rggplot2

解决方案


这有点小技巧,但forcats可能会对您有所帮助。本周早些时候我做了一个类似的帖子:

如何按类别分解子组?


首先是一些基础数据

set.seed(123)
raw_data <-
  tibble(
    x = rep(1:20, each = 6),
    rand = sample(1:120, 120) * (x/20), 
    group = rep(letters[1:6], times = 20),
    cat = ifelse(group %in% letters[1:3], "group 1", "group 2")
  ) %>% 
  group_by(group) %>% 
  mutate(y = cumsum(rand)) %>% 
  ungroup() 

现在,使用因子级别在颜色中创建渐变

df <-
  raw_data %>% 
  # create factors for group and category
  mutate(
    group = fct_reorder(group, y, max),
    cat = fct_reorder(cat, y, max) # ordering in the stack
  ) %>% 
  arrange(cat, group) %>% 
  mutate(
    group = fct_inorder(group), # takes the category into account first
    group_fct = as.integer(group), # factor as integer
    hue = as.integer(cat)*(360/n_distinct(cat)), # base hue values
    light_base = 1-(group_fct)/(n_distinct(group)+2), # trust me
    light = floor(light_base * 100) # new L value for hcl()
  ) %>% 
  mutate(hex = hcl(h = hue, l = light))

scale_fill_manual()

area_colors <-
  df %>% 
  distinct(group, hex)

最后,制作你的情节

ggplot(df, aes(x, y, fill = group)) +
  geom_area(position = "stack") +
  scale_fill_manual(
    values = area_colors$hex,
    labels = area_colors$group
  )

在此处输入图像描述


推荐阅读