2016-12-22 29 views
0

每个变量我有以下的数据帧:GGPLOT2箱线图用于利用不对等的距离

date  DGS1MO DGS3MO DGS6MO DGS1 DGS2 DGS3 DGS5 DGS7 DGS10 DGS20 DGS30 
1 2006-02-28 4.47 4.62 4.74 4.73 4.69 4.67 4.61 4.57 4.55 4.70 4.51 
2 2006-03-31 4.65 4.63 4.81 4.82 4.82 4.83 4.82 4.83 4.86 5.07 4.90 
3 2006-04-28 4.60 4.77 4.91 4.90 4.87 4.87 4.92 4.98 5.07 5.31 5.17 
4 2006-05-31 4.75 4.86 5.08 5.07 5.04 5.03 5.04 5.06 5.12 5.35 5.21 
5 2006-06-30 4.54 5.01 5.24 5.21 5.16 5.13 5.10 5.11 5.15 5.31 5.19 
6 2006-07-31 5.02 5.10 5.18 5.11 4.97 4.93 4.91 4.93 4.99 5.17 5.07 

使用(从reshape2)熔体我得到这个数据帧:

date  variable value 
1 2006-02-28 DGS1MO 4.47 
2 2006-03-31 DGS1MO 4.65 
3 2006-04-28 DGS1MO 4.60 
4 2006-05-31 DGS1MO 4.75 
5 2006-06-30 DGS1MO 4.54 
6 2006-07-31 DGS1MO 5.02 

正如你可以看到我有1,3,6个月,以及10,20,30年的时间范围。我想绘制则每列的盒须图,并有下面的代码:

bwplot <- ggplot(df, aes(x = variable, y = value, color = variable)) + 
    stat_boxplot(geom = "errorbar") + 
    geom_boxplot() + 
bwplot 

然而,问题是箱线图之间的距离(空间),每个变量是相同的。理想情况下,1个月和3个月的箱形图之间应该有非常小的距离。而且10年和20年的箱型图之间的差距应该很大。为了弥补,我试图将变量转换成数字(1/12,3/12,6/12,1,2,等等),然后尝试这种代码:

levels(df$variable) <- c(0.83, 0.25, 0.5, 1, 2, 3, 5, 7, 10, 20, 30) 

bwplot <- ggplot(df, aes(x = as.numeric(as.character(df$variable)), y = value, color = variable)) + 
    stat_boxplot(geom = "errorbar") + 
    geom_boxplot() + 
bwplot 

但是我得到只有一个在整个时间跨度巨大的箱线图,然后这样的警告信息:

Warning messages: 
1: Continuous x aesthetic -- did you forget aes(group=...)? 

如果我尝试

group = variable 

我得到

Error: Continuous value supplied to discrete scale 

这样做的正确方法是什么?

谢谢。

回答

1
s<-data.frame(date=seq(as.Date("2006-02-01"), by="month", length.out=6), M1=rnorm(6,5,0.5), M3=rnorm(6,5,0.5), M6=rnorm(6,5,0.5), Y1=rnorm(6,5,0.5), Y2=rnorm(6,5,0.5), Y3=rnorm(6,5,0.5), Y10=rnorm(6,5,0.5), Y20=rnorm(6,5,0.5), Y30=rnorm(6,5,0.5)) 

require(ggplot2) 
require(reshape2) 
s.melted<-melt(s, id.var="date") 

#Create an axis where the numbers represent the number of months elapsed 
s.melted$xaxis <-c("M"=1, "Y"=12)[sub("(M|Y)([0-9]+)","\\1",s.melted$variable)] * as.numeric(sub("(M|Y)([0-9]+)","\\2",s.melted$variable)) 

s.melted[sample(1:nrow(s.melted),6),] 
     date variable value xaxis 
23 2006-06-01  Y1 4.645595 12 
38 2006-03-01  Y10 5.190710 120 
25 2006-02-01  Y2 4.831788 24 
50 2006-03-01  Y30 3.892580 360 
39 2006-04-01  Y10 4.513831 120 
31 2006-02-01  Y3 4.357127 36 

# Only show the ticks for variable 
bwplot <- ggplot(s.melted, aes(x = xaxis, y = value, color = variable)) + 
    stat_boxplot(geom = "errorbar") + 
    geom_boxplot() + scale_x_continuous(breaks=s.melted$xaxis, 
            labels=s.melted$variable) 
bwplot 

Plot with corrected distance