2015-10-06 93 views
1

R中的多个情节我有大约20年的日常数据的时间序列。它包含日期,降雨量和其他数据。 我正在尝试绘制降雨量与时间的关系图。我想要获得20个不同颜色的线条图,并且会生成一个图表,显示一个图表中的年份。我尝试了下面的代码,但它没有给我想要的结果。任何建议来解决我的问题将是最受欢迎的绘制了不同的日历日期

library(ggplot2) 
library(seas) 
data(mscdata) 
p<-ggplot(data=mscdata,aes(x=date,y=precip,group=year,color=year)) 
p+geom_line()+scale_x_date(labels=date_format("%m"),breaks=date_breaks("1 months")) 
+3

我劝你重新创建与20日线在20种颜色的曲线。它很可能看起来很乱。你可能想看看'facet_wrap'或'facet_grid'。 – Jaap

+0

我知道它会看起来凌乱,但我想做这个阴谋。 – Joan

+0

它不仅看起来很混乱,而且年份会重叠,因此只有最大和最近的年份才会显现。你能解释一下你感兴趣吗?干湿两年?每月平均降雨量? – RHA

回答

0

它看起来不错,但这里是一种方法。我们首先迫使数据到日期在同一年:

mscdata$dayofyear <- as.Date(format(mscdata$date, "%j"), format = "%j") 

然后我们情节:

library(ggplot2) 
library(scales) 
p <- ggplot(data = mscdata, aes(x = dayofyear, y = precip, group = year, color = year)) 
p + geom_line() + 
    scale_x_date(labels = date_format("%m"), breaks = date_breaks("1 months")) 

enter image description here

0

虽然我@Jaap同意,这未必是最好的方式描绘这些数据,尝试以下操作:

mscdata$doy <- as.numeric(strftime(mscdata$date, format="%j")) 

ggplot(data=mscdata,aes(x=doy,y=precip,group=year)) + 
geom_line(aes(color=year)) 

enter image description here

0

虽然给出的答案是好回答您的问题,因为它代表,我不认为这将解决您的问题。我认为你应该以不同的方式呈现数据。 @Jaap已经建议使用方面。举例来说,这种方法:

#first add a month column to your dataframe 
mscdata$month <- format(mscdata$date, "%m") 

#then plot it using boxplot with year on the X-axis and month as facet. 
p1 <- ggplot(data = mscdata, aes(x = year, y = precip, group=year)) 
p1 + geom_boxplot(outlier.shape = 3) + facet_wrap(~month) 

这会给你一个图表每月,显示每年相邻的降雨量。因为我使用boxplot,所以降雨中的高峰显示为点(“正常”降雨事件在框内)。其他可能的方法是使用stat_summary