我想要一个堆叠条形图。我使用 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
< /p>
我唯一得到的是:
ggplot(dataset_monthly, aes(x = dataset_monthly$Date, y =dataset_monthly$????)) +
+ geom_bar(stat = "stack")
答案 0 :(得分:3)
我们可以先重塑为“长”格式
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")
答案 1 :(得分:2)
使用 geom_bar
稍作修改。感谢阿克伦!
library(tidyverse)
# Bring data in longformat -> same code as akruns!
df <- dataset_monthly %>%
pivot_longer(cols = -Date, names_to = 'Feature')
ggplot(df, aes(x=Date, y=value, fill=Feature, label = value)) +
geom_bar(stat="identity")+
geom_text(size = 3, position = position_stack(vjust = 0.8)) +
scale_fill_brewer(palette="Paired")+
theme_classic()