首页 > 解决方案 > ggplot中的堆积条形图

问题描述

我想要一个堆叠的条形图。我使用 lubridate 成功创建了我的数据框,但是因为我只能指定 x 和 y 值,所以我不知道如何“输入”我的数据值。

数据框看起来像这样:

Date           Feature1    Feature2    Feature3
2020-01-01     72          0           0
2020-02-01     90          21          5
2020-03-01     112         28          2
2020-04-01     140         36          0
...

日期应该在 x 轴上,每一行代表条形图中的一个条形(条形的高度是Feature1+ Feature2+Feature3

我唯一得到的是:

ggplot(dataset_monthly, aes(x = dataset_monthly$Date, y =dataset_monthly$????)) + 
+   geom_bar(stat = "stack") 

标签: rggplot2dplyrbar-chart

解决方案


我们可以先重塑为“长”格式

library(dplyr)
library(tidyr)
library(ggplot2)
dataset_monthly %>%
    pivot_longer(cols = -Date, names_to = 'Feature') %>%
    ggplot(aes(x = Date, y = value, fill = Feature)) +
         geom_col()

-输出

在此处输入图像描述

数据

dataset_monthly <- structure(list(Date = 
  structure(c(18262, 18293, 18322, 18353), class = "Date"), 
    Feature1 = c(72L, 90L, 112L, 140L), Feature2 = c(0L, 21L, 
    28L, 36L), Feature3 = c(0L, 5L, 2L, 0L)), row.names = c(NA, 
-4L), class = "data.frame")

推荐阅读