【问题标题】:plot data grouped by year按年份分组的绘图数据
【发布时间】:2014-04-29 13:13:25
【问题描述】:

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

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 月之间的所有月份。我已使用 zoo 加载数据:

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

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

谢谢, 安德烈亚

【问题讨论】:

  • 综合考虑函数?意思是?最大限度?分钟? sd?
  • 可能“分组”不是正确的术语,抱歉。我的意思是我想显示所有数据,但每年都应该单独绘制成一条线。
  • 好的,我想你已经找到答案了。祝你好运。

标签: r plot zoo


【解决方案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()

【讨论】:

  • 我会添加 geom_line(aes(colour = year) 来映射它。
  • 调用第一个 strsplit 返回错误:$.zoo(temp, date) 中的错误:对于单变量动物园系列是不可能的。我也尝试过使用 read.csv 而不是 read.zoo,但 strsplit 返回: strsplit(temp$date, "-") 中的错误:非字符参数。
  • 您也可以使用format 提取yearmon 对象的相关部分。 ym &lt;- as.yearmon("04-2014", format = "%m-%Y"); format(ym, "%Y"); format(ym, "%m")
  • 好的,我使用了 read.csv 而不是 read.zoo 和 yearmon 的格式化程序,它运行良好。谢谢大家!
【解决方案2】:

这里有几种方法。首先设置数据。注意read.zoo 中的简化。

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

除了下面的图之外,R(统计数据包)的基础中还有monthplot。如果temp 是问题中提供的数据子集,则它似乎不适用于as.ts(temp),但如果实际数据看起来更像?monthplot 示例中的数据,那么它会起作用。

1) ggplot2

创建一个 data.frame DF,其中包含月份、年份和值的列。 cycle 可以得到月份数字,格式为%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)

2) lattice 使用 2) 中的 DF 可以:

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

修订添加了解决方案和附加评论。

【讨论】:

    猜你喜欢
    • 2015-10-28
    • 2019-06-18
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2017-11-04
    • 2011-12-13
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多