簡體   English   中英

ggplot2:將多個箱圖​​排列為時間序列

[英]ggplot2: arranging multiple boxplots as a time series

我想用ggplot2創建一個多變量箱圖時間序列,我需要有一個x軸,根據相關日期定位箱圖。

我發現了兩個關於這個問題的帖子:一個是使用ggplot2的時間序列圖,但是x軸不是scale_x_axis,所以圖表在我的情況下有偏差。 另一個是ggplot2:R中有scale_x_date軸的多個因子boxplot,但是人使用了我在我的情況下不使用的交互功能。

這是一個示例文件和我的代碼:

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) ) `

有人可以幫我解決這個問題嗎?

這是你想要的嗎?

在此輸入圖像描述

碼:

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

關鍵是按interaction(date, trmt)分組interaction(date, trmt)以便獲得所有框,而不是將asDate轉換為因子,以便ggplot將其視為日期。 如果要向x軸添加更多內容,請務必使用+ scale_x_date().

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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