每个标记的堆积条的不同颜色?

Different colours for each labelled stacked bar?

如何制作堆积条形图,使每个堆积条的每个段都有不同的颜色(即独特颜色与所有条的总段一样多 - 在本例中为 7 种不同颜色)。

我已经尝试了这些方法 here,但由于输入数据的格式不同而得到不同的结果,并且该问题显示总数并且不需要图例(我需要图例)。

MRE + 到目前为止的尝试

library(tidyverse)

df <- structure(list(discipline = c("Dev Ops", "Dev Ops", "Dev Ops", 
"Dev Ops", "Data Engineering", "Data Engineering", "Data Engineering"
), work_type = c("Casual/Vacation", "Contract/Temp", "Full Time", 
"Part Time", "Casual/Vacation", "Contract/Temp", "Full Time"), 
    n = c(3L, 117L, 581L, 9L, 1L, 297L, 490L)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -7L))

# A tibble: 7 x 3
  discipline       work_type           n
  <chr>            <chr>           <int>
1 Dev Ops          Casual/Vacation     3
2 Dev Ops          Contract/Temp     117
3 Dev Ops          Full Time         581
4 Dev Ops          Part Time           9
5 Data Engineering Casual/Vacation     1
6 Data Engineering Contract/Temp     297
7 Data Engineering Full Time         490

这会生成正确的堆积条形图,但两个堆积条的颜色相同

df %>% 
  ggplot(aes(x = discipline, y = n, fill = work_type)) +
    geom_col(position = "Stack")

这对每个堆叠条应用独特的颜色,但对两个堆叠条应用相同

cols <- c("#5E4FA2", "#5E4FA2CC", "#5E4FA299", "#5E4FA266", "#9E0142", 
"#9E0142CC", "#9E014299")
df %>% 
  ggplot(aes(x = discipline, y = n, fill = work_type)) +
    geom_col(position = "Stack") +
  scale_fill_manual(values = cols[1:4])

这会在两个堆叠条上实现不同的颜色,但颜色错误(和图例错误)

df %>% 
  ggplot(aes(x = discipline, y = n, fill = cols)) +
    geom_col(position = "Stack")

这是基于 this 方法,但请注意条形高度与所有条形(而不是每个条形)的总和相匹配,并且两个堆叠条形中的颜色也相同

df %>% 
  pivot_longer(cols = discipline:work_type) %>% 
  ggplot(aes(x = name, y = n)) + 
  geom_col(fill = c(cols, cols))

如果你想要两个结合两个因素,通常的技巧是使用 interaction() 所以你的代码将是:

# Data 
df <- structure(list(discipline = c("Dev Ops", "Dev Ops", "Dev Ops", 
"Dev Ops", "Data Engineering", "Data Engineering", "Data Engineering"
), work_type = c("Casual/Vacation", "Contract/Temp", "Full Time", 
"Part Time", "Casual/Vacation", "Contract/Temp", "Full Time"), 
    n = c(3L, 117L, 581L, 9L, 1L, 297L, 490L)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -7L))

# Colours
cols <- c("#5E4FA2", "#5E4FA2CC", "#5E4FA299", "#5E4FA266", "#9E0142", 
"#9E0142CC", "#9E014299")

# Plot
df %>% 
  ggplot(aes(x = discipline, y = n, fill = interaction(work_type, discipline))) +
  geom_col(position = "Stack") +
  scale_fill_manual(name="Whatever", values = cols)

尽管如此,您可能想要一个更好的颜色图例名称,并且可能想要调查 interactionsep 参数,以便因子更具可读性。