[英]Stacked Bar Chart in ggplot
I would like to have a stacked bar-chart.我想要一个堆叠的条形图。 I succesfully created my dataframe using lubridate, however as I can just specify x and y values I do not know how to 'put in' my data values.
我使用 lubridate 成功创建了我的 dataframe,但是因为我只能指定 x 和 y 值,所以我不知道如何“输入”我的数据值。
The dataframe is looking like so: dataframe 看起来像这样:
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
...
The date should be on the x-axis and each row represents one bar in the bar chart (the height of the bar is the sum of Feature1
+ Feature2
+ Feature3
日期应该在 x 轴上,每一行代表条形图中的一个条形(条形的高度是
Feature1
+ Feature2
+ Feature3
的总和
The only thing I get is this:我唯一得到的是:
ggplot(dataset_monthly, aes(x = dataset_monthly$Date, y =dataset_monthly$????)) +
+ geom_bar(stat = "stack")
We can reshape to 'long' format first我们可以先重塑为“长”格式
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()
-output -输出
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")
Slightly modified using geom_bar
.使用
geom_bar
修改。 thanks to akrun!感谢阿克伦!
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.