簡體   English   中英

如何隨時間(24 小時)在 R 中創建堆積面積圖?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM