【发布时间】:2019-07-19 02:24:25
【问题描述】:
我有以下具有三种不同成本类型和年份列的示例数据:
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 轴应该是堆积成本。
【问题讨论】:
-
你想做什么对我来说不是很清楚,但是像这样??
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_bar(stat = "identity")