绘制r中的月度和年度天气数据

时间:2013-04-17 17:39:55

标签: r plot ggplot2 lattice

我正在尝试开发天气数据中出现的天气情节 - 类似于。

enter image description here

我想绘制每日价值(虽然平均值可以显示在圆圈中)。我正在使用ggplot2因为它需要多方面(每个月和每年)。

st <- as.Date ("2009-1-1")
en <- as.Date ("2011-12-28")
date1 <- seq(st, en, "1 day")
year <- format(date1, "%Y")
month <- format (date1, "%b")
day <- as.numeric (format(date1, "%d"))

avgtm <- round (rnorm (length(date1), 50,5), 1)
maxtm <- avgtm + abs(rnorm (length (avgtm), 0, 5))
mintm <-  avgtm - abs(rnorm (length (avgtm), 0, 5))

myd <- data.frame ( year, month, day, avgtm, maxtm, mintm)
require(ggplot2)
qplot(day, avgtm, data = myd, geom = "line", col = "red") +
facet_grid(year ~ month) + theme_bw()

enter image description here

这里有一个主要问题,线路将在几个月之间连接。

每个月都被绘制为最大值(尽管一个月可以在28个月结束,在该月留空)。 enter image description here

有没有一种聪明的方法来实现我想要实现的目标。我试过ggplot2,但可能还有其他不错的选择。

修改

我正在尝试在月份的第一天添加垂直线以标记月份。这是我试图找到一个月的第一天:

 td = as.Date (seq(as.Date("2009/1/1"), as.Date("2011/12/28"), "months"))

我试图用这个来绘制线条:

qplot(date, avgtm, data = myd, geom = "line", col = "red") +
  facet_wrap(~year, scales='free_x', ncol=1, nrow=3) +

   geom_vline(xintercept=td, linetype="dotted") + theme_bw()

但运行错误: 错误:拦截类型无效:应该是数字向量,函数或函数名称

如何用日期绘制垂直线?

2 个答案:

答案 0 :(得分:4)

如何制作日期列,然后仅限年份

myd$date <- as.Date(paste(myd$year, myd$month, myd$day), format='%Y %b %d')

qplot(date, avgtm, data = myd, geom = "line", col = "red") +
  facet_wrap(~year, scales='free_x', ncol=1, nrow=3)

enter image description here

您也可以将scales='free_x'添加到您的情节中,但会发现它会使解释变得困难。

通过月份和年份的分面,您告诉观察者和绘图工具绘制的变量不是连续的。这是不正确的,正如您在问题中指出的那样。因此,没有刻面......如果需要,您可以为每个月或每天添加刻度线。

library(scales)
qplot(date, avgtm, data = myd, geom = "line", col = "red") +
      facet_wrap(~year, scales='free_x', ncol=1, nrow=3) +
      scale_x_date(breaks=date_breaks("month"), labels=date_format("%b"))

或者你可以提取day of year并在一个地块上绘制所有内容,按年份着色:

myd$doy <- format(myd$date, '%j')
p <- ggplot(myd, aes(x=doy, y=avgtm, color=year, group=year))

p + geom_line()

p + geom_smooth()

答案 1 :(得分:3)

来自panel.xblocks的{​​{1}}有一个解决方案:

latticeExtra

我定义了两个函数来提取月份和年份值而不是 将它们包含在st <- as.Date("2009-1-1") en <- as.Date("2011-12-28") date1 <- seq(st, en, "1 day") avgtm <- round (rnorm (length(date1), 50,5), 1) myd <- data.frame(date1, avgtm) 中。这种方法很有用 data.frame函数panel.xblocks中的panel

xyplot

我使用month <- function(x)format(x, '%m') year <- function(x)format(x, '%Y') 作为条件变量来产生三个 面板。这些面板中的每一个都将显示该时间序列 year(year(date1))和一系列连续的块 交替颜色以突出显示月份(panel.xyplot)。您 应该注意panel.xblocks中的y参数是。{ 先前定义的函数panel.xblocks

month

xblocks

相关问题