我想按年份或月份对时间进行绘图,现在我有了每日数据,如何将每日绘图更改为每月绘图或年度绘图?
我有2013年1月1日至2017年12月31日的数据,示例数据如下:
dput(head(Incidence_byday,n=20))
structure(list(DATE = structure(c(15706, 15707, 15708, 15709, 15710, 15711, 15712,
15713, 15714, 15715, 15716, 15717, 15718, 15719,
15720, 15721, 15722, 15723, 15724, 15725),
class = "Date"),
Inpatient = c(5L, 7L, 3L, 52L, 111L, 150L, 177L, 251L, 292L, 321L, 338L,
178L, 124L, 346L, 368L, 354L, 375L, 461L, 220L, 148L),
HAI = c(0, 0, 0, 4, 1, 1, 3, 10, 8, 13, 9, 0, 12, 10, 11, 11, 15, 10, 7, 8),
Incidence = c(0, 0, 0, 7.69230769230769, 0.900900900900901, 0.666666666666667,
1.69491525423729, 3.98406374501992, 2.73972602739726,
4.04984423676012, 2.66272189349112, 0, 9.67741935483871,
2.89017341040462, 2.98913043478261, 3.10734463276836,
4, 2.16919739696312, 3.18181818181818, 5.40540540540541)),
row.names = c(NA, 20L), class = "data.frame")
#install.packages("ggplot2")
#install.packages("lubridate")
library(ggplot2)
library(lubridate)
theme_set(theme_bw())
ggplot(Incidence_byday, aes(x=DATE)) +
geom_line(aes(y=Incidence)) +
labs(title="Incidence trend", y="Incidence %")
结果如下:
答案 0 :(得分:0)
要获取其他时间段的发生率,您可以使用lubridate
将每个DATE分配给特定的星期,月份或年份,然后使用group_by
+ summarize
和{ {1}},以获取该时间段内的统计信息:
mutate
然后使用新数据进行绘图:(在这种情况下,按周进行,因为原始数据全部在一个月和一年中)
library(tidyverse); library(lubridate)
Incidence_byweek <- Incidence_byday %>%
group_by(DATE = floor_date(DATE, "7 days")) %>% # e.g., or "1 month" or "1 year"
summarize(Inpatient = sum(Inpatient),
HAI = sum(HAI)) %>%
mutate(Incidence = 100 * HAI / Inpatient)