r - 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")
解决方案
我们可以先重塑为“长”格式
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")
推荐阅读
- java - 从一个对象到另一个对象的Java条件映射?
- asp.net-core - 我们如何在asp.net 2.1核心应用程序的启动类中注册IHttpContextAccessor?
- r - 如何在 R 中查找
- python - 更改散点图中的标记大小
- python-asyncio - asyncio 的 call_soon 失败,而 create_task 没有
- javascript - 在 Xamarin.Forms WebView 中执行 Javascript
- c# - WPF C#设置为自动后获取网格高度
- ios - 在 xCode 存档的导出中,如何从命令行禁用目标签名
- vba - 使用书签访问 Word,如果书签留空,如何执行操作
- php - 如何在 div 标签中添加占位符