[英]How to create a stacked area chart in R over time (24 hours)?
我正在尝试在 R Studio 中创建一个堆积面积图来表示我在正常的 24 小时一天内在我生活的不同领域的生产力。
这是我的数据集的一个片段:
Time Coursework Leisure Intern PD
1 00:00 0 0 0 0
2 01:00 0 0 0 0
3 02:00 0 0 0 0
4 03:00 0 0 0 0
5 04:00 0 0 0 0
6 05:00 1 0 0 0
7 06:00 1 0 0 2
8 07:00 6 1 0 6
9 08:00 17 1 0 1
10 09:00 18 0 0 1
我最挣扎的部分是如何格式化我的 CSV 文件并将所有这些数据组合在一起。 我完全不知道如何在一天 24 小时的背景下构建这些数据。 任何人都可以帮我开始这个吗?
您可以尝试这种tidyverse
方法。 您必须将数据格式化为长格式。 为了显示时间,您可以使用factor()
破解它。 这里的代码:
library(tidyverse)
#Code
df %>% pivot_longer(-Time) %>%
ggplot(aes(x=factor(Time),y=value,color=name,group=name))+
geom_line()+
xlab('Time')
输出:
使用的一些数据:
#Data
df <- structure(list(Time = c("00:00", "01:00", "02:00", "03:00", "04:00",
"05:00", "06:00", "07:00", "08:00", "09:00"), Coursework = c(0L,
0L, 0L, 0L, 0L, 1L, 1L, 6L, 17L, 18L), Leisure = c(0L, 0L, 0L,
0L, 0L, 0L, 0L, 1L, 1L, 0L), Intern = c(0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L), PD = c(0L, 0L, 0L, 0L, 0L, 0L, 2L, 6L, 1L, 1L
)), class = "data.frame", row.names = c("1", "2", "3", "4", "5",
"6", "7", "8", "9", "10"))
只需将 @Duck 更改为 area 并使用tidyverse
来简化数据定义:
library(tidyverse)
library(ggplot2)
df <- tribble(
~rn, ~RecordTime, ~Coursework, ~Leisure, ~Intern, ~PD,
1, "00:00", 0, 0, 0, 0,
2, "01:00", 0, 0, 0, 0,
3, "02:00", 0, 0, 0, 0,
4, "03:00", 0, 0, 0, 0,
5, "04:00", 0, 0, 0, 0,
6, "05:00", 1, 0, 0, 0,
7, "06:00", 1, 0, 0, 2,
8, "07:00", 6, 1, 0, 6,
9, "08:00", 17, 1, 0, 1,
10, "09:00", 18, 0, 0, 1,
)
#x <-
df %>%
pivot_longer(-c(RecordTime)) %>%
filter(name != "rn") %>%
ggplot(aes(x=RecordTime,y=value,group=name, color=name, fill = name))+
geom_area()
这可能有效: ggplot('data', aes('x', 'y')) + geom_smooth(aes(fill = 'variables'), color = 'choose line color')看看代码是如何工作的
您必须以变量(课程作业、实习生等)在一列中的方式排列数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.