ggplot2:将多个箱图​​排列为时间序列

时间:2015-02-27 14:43:55

标签: r ggplot2 time-series boxplot

我想用ggplot2创建一个多变量箱图时间序列,我需要有一个x轴,根据相关日期定位箱图。

我发现了两个关于这个问题的帖子:一个是Time series plot with groups using ggplot2但是x轴不是scale_x_axis所以图表在我的情况下有偏差。另一个是ggplot2 : multiple factors boxplot with scale_x_date axis in R,但是这个人使用了我在我的情况下不使用的交互功能。

这是一个示例文件和我的代码:

dtm <- read.table(text="date ruche mortes trmt      
03.10.2013     1      8   P+        
04.10.2013     1      7   P+        
07.10.2013     1     34   P+       
03.10.2013     7     16   P+       
04.10.2013     7     68   P+       
07.10.2013     7    170   P+
03.10.2013     2      7   P-        
04.10.2013     2      7   P-       
07.10.2013     2     21   P-      
03.10.2013     5      8   P-       
04.10.2013     5     27   P-      
07.10.2013     5     24   P- 
03.10.2013     3     15    T       
04.10.2013     3      6    T    
07.10.2013     3     13    T    
03.10.2013     4      6    T    
04.10.2013     4     18    T    
07.10.2013     4     19    T ", h=T)

require(ggplot2)
require(visreg)
require(MASS)
require(reshape2)
library(scales)

dtm$asDate = as.Date(dtm[,1], "%d.%m.%Y")

## Plot 1: Nearly what I want but is biased by the x-axis format where date should not be a factor## 

p2<-ggplot(data = dtm, aes(x = factor(asDate), y = mortes)) 
p2 +  geom_boxplot(aes(fill = factor(dtm$trmt))) 

## Plot 2: Doesn't show me what I need, ggplot apparently needs a factor as x## 

p<-ggplot(data = dtm, aes(x = asDate, y = mortes)) 
p +  geom_boxplot(aes( group = asDate, fill=trmt) ) `

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:4)

这是你想要的吗?

enter image description here

代码:

p <- ggplot(data = dtm, aes(x = asDate, y = mortes, group=interaction(date, trmt)))
p +  geom_boxplot(aes(fill = factor(dtm$trmt)))

关键是按interaction(date, trmt)进行分组,以便获得所有框,而不是将日期转换为因子,以便ggplot将其视为日期。如果要向x轴添加更多内容,请务必使用+ scale_x_date().