首页 > 解决方案 > 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 轴上应该是堆叠成本。

例子

标签: rggplot2bar-chart

解决方案


您必须将汇总数据转换为整洁(-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)更改为键值对。

在此处输入图像描述


推荐阅读