【发布时间】:2020-05-07 14:21:04
【问题描述】:
如何制作堆积条形图,使其每个堆积条的每个段都有不同的颜色(即,与所有条的总段一样多的唯一颜色 - 在本例中为 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))
【问题讨论】:
标签: r ggplot2 geom-bar geom-col