每个变量的 ggplot2 箱线图不等距离

ggplot2 boxplot for each variable with unequal distance

我有以下数据框:

  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

使用 melt(来自 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

但是,问题是每个变量的箱线图之间的距离 (space) 是相同的。理想情况下,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

正确的做法是什么?

谢谢。

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