[英]How to make a timeseries boxplot in R
I'm trying to make a time series boxplot using ggplot2
. 我正在尝试使用
ggplot2
创建一个时间序列ggplot2
。
I have montly values for many individuals. 我对很多人都有价值观。
I need to make a timeseries boxplot by month with my data. 我需要用我的数据按月制作一个时间箱箱图。
I think that my problem is how to create a factor (month) with my data. 我认为我的问题是如何用我的数据创建一个因子(月)。
p <- ggplot(mydata, aes(factor(date), measure))
另一种方法是不必更改日期格式并进行任何排序等,只需将日期添加为分组因子,如下所示:
ggplot(mydata) + geom_boxplot(aes(x = date, y = measure, group = date))
Updated: Based on OP's clarification that multiple years have to be handled separately. 更新:根据OP的说明,多年必须单独处理。
library(ggplot2)
#generate dummy data
date_range <- as.Date("2010/06/01") + 0:400
measure <- runif(401)
mydata <- data.frame(date_range, measure)
# create new columns for the months and years, and
# and a year_month column for x-axis labels
mydata$month <- format(date_range, format="%b")
mydata$year <- as.POSIXlt(date_range)$year + 1900
mydata$year_month <- paste(mydata$year, mydata$month)
mydata$sort_order <- mydata$year *100 + as.POSIXlt(date_range)$mon
#plot it
ggplot(mydata) + geom_boxplot(aes(x=reorder(year_month, sort_order), y=measure))
Which produces: 哪个产生:
Hope this helps you move forward. 希望这有助于您前进。
I create a function to create the plot you need. 我创建了一个函数来创建你需要的图。
the function is: 功能是:
ts_plot_season <- function(x = x) {
season <- cycle(x)
season.factor <- factor(season)
ggplot() +
geom_boxplot(mapping = aes(x = season.factor,
y = x)) +
labs(x = "Periodo", y = "Serie")
}
Fox example: Fox例子:
ts_plot_season(AirPassengers)
I hope this help. 我希望这有帮助。 I know this question is old, but i couldn't find some god answer on the web.
我知道这个问题很老,但我在网上找不到一些上帝的答案。 So i think this will help to someone.
所以我认为这对某人有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.