2012-11-05 41 views
0

我有温度记录,如数据集与温度记录[R箱图:阴谋年和月

row.names Collection_date temprature col_yr col_mnth 
    1 1  4-Aug-04   27  2004 8 
    2 2  9-Aug-04   26  2004 8 
    3 3  4-Aug-04   27  2004 8 
    4 4  9-Aug-04   26  2004 8 
    5 5  9-Aug-04   26  2004 8 
    6 6  9-Aug-04   26  2004 8 
... 
1031 1031  6-Aug-06   32  2006 8 

我想创建R中箱线图中包含X轴:

1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 ... 
     2004       2005 

回答

2

这是不是一个非常优雅的解决方案,但它是我能想到的唯一的,所以你的箱子有适当的宽度。

鉴于您的样本数据:

dat <- read.table(textConnection("row.names Collection_date temprature col_yr col_mnth 
    1 1 4-Aug-04 27 2004 8 
    2 2 9-Aug-04 26 2004 8 
    3 3 4-Aug-04 27 2004 8 
    4 4 9-Aug-04 26 2004 8 
    5 5 9-Aug-04 26 2004 8 
    6 6 9-Aug-04 26 2004 8 
    1031 1031 6-Aug-06 32 2006 8")) 

首先声明日期为POSIXct对象(注意,在你的情况,你必须确保你的本地设置的英语,因为您的几个月都是英文缩写):

dat$Collection_date <- strptime(dat$Collection_date,"%d-%b-%y") 

然后创建了年个月的序列:

ax_month <- seq(min(dat$Collection_date),max(dat$Collection_date),"month") 
ax_year <- seq(min(dat$Collection_date),max(dat$Collection_date),"year") 

然后画一个空的情节与轴:

plot(NA, xaxt="n",type="n", ylab="Temperature", xlab=NA, 
    xlim=range(seq_along(ax_month)), ylim=range(dat$temprature)) 
axis(3,at=seq_along(ax_month), labels=format(ax_month,"%m")) 
mtext(format(ax_year,"%Y"), side=3, line=3, at=seq(1,length(ax_month), by=12)) 

最后每月箱线图:

for(i in seq_along(ax_month)){ 
    sub_dat <- dat[format(dat$Collection_date, "%m-%Y") == format(ax_month[i], "%m-%Y"),] 
    boxplot(sub_dat$temprature, add=TRUE, axes=FALSE, at=i) 
    } 

显然给你给数据的样本,这里的结果是不是很漂亮,但我想这是实际的数据会很好地填满。

enter image description here

但这里是它看起来像一些(虚构的)什么更完整的数据:

enter image description here

+0

非常感谢您的详细解答。我试过这个代码。我可以绘制网格,但循环给出了一个错误:警告消息: 1:在min(x)中:没有非缺少参数min;返回Inf –

+0

我终于可以将它运用了。谢谢。 –