按年分组的绘图数据

时间:2014-04-29 13:13:25

标签: r plot zoo

我正在尝试创建一个温度图,但我无法按年汇总数据。 我的数据以这种形式出现:

02-2012 7.2
02-2013 7.2
02-2010 7.9
02-2011 9.8
03-2013 10.7
03-2010 13.1
03-2012 18.5
03-2011 13.7
02-2003 9.2
...

包含2000年1月到2013年12月之间的所有月份。我已经在动物园中加载了数据:

f <- function(x) as.yearmon(format(x), "%m-%Y")
temp <- read.zoo(file="results.tsv", FUN = f)

绘制临时变量我从2000年1月到2013年12月获得了X轴的图,但我想要的是X轴从1月到12月的绘图,并绘制每年的温度作为一个单独的行。任何提示?

谢谢, 安德烈

2 个答案:

答案 0 :(得分:1)

首先,您要将日期分为年度和月份组成部分:

names(temp) <- c("date","temperature")
tmpSplit <- strsplit(temp$date, "-")
temp$month <- sapply(tmpSplit, "[", 1)
temp$year <- sapply(tmpSplit, "[", 2)

然后,我倾向于使用ggplot2包来绘制数据:

library(ggplot2)
ggplot(temp, aes(x=month, y=temperature, group=year)) + geom_line()

答案 1 :(得分:0)

以下是几种方法。首先设置数据。请注意read.zoo

中的简化
library(zoo)
temp <- read.zoo("results.tsv", FUN = as.yearmon, format = "%m-%Y")

除了下面的图表,R(stats包)的基础中还有monthplot。如果as.ts(temp)是问题中提供的数据子集,但它似乎不适用于temp,但如果实际数据看起来更像?monthplot示例中的数据,那么它就可以正常工作。

1)ggplot2

使用月,年和值的列创建data.frame DFcycle可以获得月份数字和格式为%Y的格式可以给出年份。 请注意,我们希望年份是数据框使它们成为格式为字符的结果的因素。最后使用ggplot2或lattice:

创建绘图
library(ggplot2)
DF <- data.frame(Month = coredata(cycle(temp)), 
                 Year = format(index(temp), "%Y"),
                 Value = coredata(temp))

ggplot(DF, aes(Month, Value, col = Year)) + 
           geom_line() + 
           scale_x_continuous(breaks = 1:12)

ggplot2 screenshot

2)格子使用2)中的DF这将起作用:

library(lattice)
xyplot(Value ~ Month, DF, group = Year, type = "l", auto = TRUE)

xyplot screenshot

已修订已添加解决方案和其他评论。

相关问题