1

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

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

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")

在此处输入图像描述

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

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

在此处输入图像描述

4

1 回答 1

1

如果你想要两个结合两个因素,通常的技巧是使用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)

代码输出图

不过,您可能想要一个更好的颜色图例名称,并且可能想要调查sep参数以interaction使这些因素更具可读性。

于 2020-05-07T14:39:21.047 回答