[英]How to plot time series data with ggplot2 in R
我有一個看起來像這樣的數據。
head(histogram)
year month day create verified trans
1 2015 12 10 2 2 2
2 2015 12 14 3 1 NA
3 2016 1 6 1 NA NA
4 2016 1 15 1 NA NA
5 2016 1 17 1 1 NA
6 2016 1 25 1 NA NA
年,月,日在單獨的列中。 我希望按周繪制條形圖分組。
例如,從2016-1-1到2016-1-6的數據將在x軸上分組,以產生3條:與創建,驗證,反式對應的所有創建的總和。 我更喜歡使用ggplot2,但一切都很好。
當您要使用時間序列和ggplot2
時,建議使用POSIX
格式。
請注意,您必須處理第00周,這是一月的第一天,即12月的第52周。
## Fake data / without a reproducible example
set.seed(1)
df = data.frame(year = c(rep(2015,14), rep(2016,21)),
month = c(rep(12,14), rep(01,21)), day = c(seq(18,31,1), seq(01,21,1)),
create = sample(c(1,2,3,NA),35, replace = T, prob = c(0.3,0.3,0.3,0.1)),
verified = sample(c(1,2,3,NA),35, replace = T, prob = c(0.1,0.1,0.1,0.7)),
trans = sample(c(1,2,3,NA),35, replace = T, prob = c(0.1,0.2,0.1,0.6)))
# Add of week information
df$date_posix = as.POSIXct(paste0(df$year, "-", df$month, "-", df$day))
df$week = strftime(df$date_posix ,format = "%W")
# summarize
require(plyr)
#> Le chargement a nécessité le package : plyr
df_sum = ddply(df, "week", summarize,
create_sum = sum(create, na.rm = T),
verified_sum = sum(verified, na.rm = T),
trans_sum = sum(trans, na.rm = T))
# melt
require(reshape2)
#> Le chargement a nécessité le package : reshape2
df_sum_melt = melt(df_sum, id = "week")
# plot
require(ggplot2)
#> Le chargement a nécessité le package : ggplot2
ggplot(df_sum_melt, aes(x = week, y = value, fill = variable)) +
geom_bar(stat = "identity", position = "dodge")
由reprex包 (v0.2.0)創建於2018-09-18。
編輯 (整理方式)
library(tidyverse)
library(lubridate)
#>
#> Attachement du package : 'lubridate'
#> The following object is masked from 'package:base':
#>
#> date
set.seed(1)
tibble(year = c(rep(2015,14), rep(2016,21)),
month = c(rep(12,14), rep(01,21)), day = c(seq(18,31,1), seq(01,21,1)),
create = sample(c(1,2,3,NA),35, replace = T, prob = c(0.3,0.3,0.3,0.1)),
verified = sample(c(1,2,3,NA),35, replace = T, prob = c(0.1,0.1,0.1,0.7)),
trans = sample(c(1,2,3,NA),35, replace = T, prob = c(0.1,0.2,0.1,0.6))) %>%
mutate(date_posix = as.Date(paste0(year, "-", month, "-", day)),
week = lubridate::week(date_posix)) %>%
group_by(week) %>%
summarise(create_sum = sum(create, na.rm = T),
verified_sum = sum(verified, na.rm = T),
trans_sum = sum(trans, na.rm = T)) %>%
gather(variable, value, -week) %>%
ggplot(., aes(x = factor(week), y = value, fill = variable)) +
geom_bar(stat = "identity", position = "dodge")
由reprex包 (v0.2.0)創建於2018-09-18。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.