【问题标题】:ggplot2: stacked barplot over different columnsggplot2:不同列上的堆叠条形图
【发布时间】: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 %&gt;% group_by(year) %&gt;% summarise(n=n(), meanA = mean(costsA), meanB = mean(costsB), meanC = mean(costsC)) %&gt;% gather("key", "value", - c(year, n)) %&gt;% ggplot(aes(x = year, y = value, group = key, fill = key)) + geom_bar(stat = "identity")

标签: r ggplot2 bar-chart


【解决方案1】:

您必须将汇总数据制作成整洁(-ish)的格式,以生成与您发布的一样的图。在 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、costB、costC)更改为键值对。

【讨论】:

  • 您可能想在这里使用geom_colgeom_bar 与案例数成正比,而geom_col 与值成正比。原始问题以 $ 作为 y 轴,不计算在内。
  • 谢谢@Dave2e。我相信geom_col()geom_bar(stat = 'identity') 相同,但我倾向于忘记geom_col() 的存在。
猜你喜欢
  • 1970-01-01
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 2012-01-04
  • 2021-12-08
  • 1970-01-01
相关资源
最近更新 更多