我有以下示例数据,其中包含三种不同的成本类型和年份列:
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 轴应为堆积成本。
最佳答案
您必须将汇总数据转换为整洁的格式才能生成像您发布的那样的绘图。在 tidy-verse 中,您可以使用 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、costsB、costC)更改为键值对。
关于r - ggplot2:不同列上的堆叠条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54870325/