r - 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))
解决方案
这有点小技巧,但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
)
推荐阅读
- android - 我在 3.6.1 中更新 android studio 后出现 gradle build 错误,请帮助解决
- sql-server - 使用 SSIS 通过电子邮件发送查询结果
- javascript - 在 Angular app.component.ts 中使用 jQuery 代码
- json - 来自请求的 Spring Rest 控制器中的任何 JSON 定义
- ios - 在iOS中检测“触摸返回通话”的点击
- hadoop - 在 Hadoop Hive 中计数并显示超过给定数量的结果
- google-sheets - Using a ArrayFormula or Query to replace dragging down SumIf between dates
- python - QMovie 不显示 Gif
- laravel - Laravel 6 迁移问题:外键约束形成错误
- python - 如何在 Anaconda Windows 10 中安装 wget?