r - ggplot2:堆叠在不同列上的条形图
问题描述
我有以下具有三种不同成本类型和年份列的示例数据:
library(tidyverse)
# Sample data
costsA <- sample(100:200,30, replace=T)
costsB <- sample(100:140,30, replace=T)
costsC <- sample(20:20,30, replace=T)
year <- sample(c("2000", "2010", "2030"), 30, replace=T)
df <- data.frame(costsA, costsB, costsC, year)
我的目标是将这些成本绘制在堆积条形图中,以便我可以比较三个年份类别之间的平均成本。为此,我汇总了这些值:
df %>% group_by(year) %>%
summarise(n=n(),
meanA = mean(costsA),
meanB = mean(costsB),
meanC = mean(costsC)) %>%
ggplot( ... ) + geom_bar()
但是我现在如何绘制图表?在 x 轴上应该有年份,在 y 轴上应该是堆叠成本。
解决方案
您必须将汇总数据转换为整洁(-ish)格式,以生成与您发布的图类似的图。在一个整洁的诗句中,您可以使用gather
将多列转换为两列键值对的函数来做到这一点。例如,以下代码生成下图。
df %>% group_by(year) %>%
summarise(n=n(),
meanA = mean(costsA),
meanB = mean(costsB),
meanC = mean(costsC)) %>%
gather("key", "value", - c(year, n)) %>%
ggplot(aes(x = year, y = value, group = key, fill = key)) + geom_col()
使用gather("key", "value", - c(year, n))
,将三列(costsA、costB、costC)更改为键值对。
推荐阅读
- excel - VBA - 数据透视表刷新 1004 应用程序未定义错误
- matlab - Simulink 家用热系统作为 AC
- mysql - 尝试添加项目时获取空的sqlite DB和“(sqlite3.OperationalError)没有这样的表:..:”
- android - 如何从后端将视频加载到应用程序中?
- android - 如何使用 ViewModel 在 Fragment 之间进行通信?
- html - 如何将 html 中的变量字符串值渲染到烧瓶中?
- python - 使用先知的时间序列预测(来自`float`的issubdtype)
- javascript - 页面重新加载时滚动事件未触发
- php - 如何仅获取列表中不同的城市?
- mysql - MySQL:别名表不存在(复杂的子查询)