所以目前我的数据集看起来像这样:
yearMon V1
1 012011 2.534161
2 012012 1.818421
3 012013 1.635179
4 012014 1.609195
5 012015 1.794979
6 022011 3.408389
7 022012 1.756303
8 022013 1.577855
9 022014 1.511905
10 022015 1.748879
11 032011 2.664336
12 032012 1.912023
13 032013 1.408602
14 032014 1.646091
15 032015 1.705069
16 042011 2.532895
17 042012 3.342926
18 042013 3.056657
我想绘制每年特定月份的平均值,IE为2011年3月,2012年3月,2013年3月,2014年3月的平均值,并在12个月中重复。我该怎么做呢?
答案 0 :(得分:3)
1)monthplot 将数据转换为zoo(使用"yearmon"
类 - 我们还在评论中显示另一个转换器),然后转到"ts"
类然后使用monthplot
(在R的基础上)与"ts"
对象(或下面我们使用autoplot.zoo
(使用ggplot2包)与zoo对象)。
library(zoo)
# to_yearmon <- function(x) as.yearmon((x %% 10000) + (x %/% 10000 - 1) / 12)
to_yearmon <- function(x) as.yearmon(sub("(.*)(....)$", "\\2-\\1", x))
ser_zoo <- read.zoo(ser_df, FUN = to_yearmon) # convert to DF to zoo
ser_ts <- as.ts(ser_zoo) # convert zoo to ts
monthplot(ser_ts)
(情节后继续)
2)autoplot.zoo 我们将展示如何在一个图表中绘制(i)每年一行(2011年,2012年,...)和(ii)在单独的面板中绘制(iii) )每月一行(1,2,3,......)全部在一个图表中,(iv)单独的小组。
我们创建一个数据框ser_df2
,其中3列代表月,年和系列的值。然后我们将这个长格式系列转换为宽格式ser_zoo2
,其中时间为1,2,3,...表示每年的月份和一列。我们还将此长格式系列转换为宽格式ser_zoo2
,时间为2011年,2012年......代表年份和每月一列。通过在单个面板和多个面板中绘制每个图表,我们得到2x2 = 4个图表,我们将在下面显示。
library(ggplot2)
library(gridExtra)
ser_df2 <- data.frame(month = cycle(ser_zoo),
year = floor(as.numeric(time(ser_zoo))),
ser = coredata(ser_zoo))
ser_zoo2 <- read.zoo(ser_df2, index = 1, split = 2) # split into one column per year
p1 <- autoplot(ser_zoo2, facet = NULL)
p2 <- autoplot(ser_zoo2)
ser_zoo3 <- read.zoo(ser_df2, index = 2, split = 1) # split into one column per month
p3 <- autoplot(ser_zoo3, facet = NULL)
p4 <- autoplot(ser_zoo3)
grid.arrange(p1, p3, p2, p4, ncol = 2)
(点击图表放大)
{{3}}
注意:我们将其用作输入数据框ser_df
:
Lines <- "
yearMon V1
1 012011 2.534161
2 012012 1.818421
3 012013 1.635179
4 012014 1.609195
5 012015 1.794979
6 022011 3.408389
7 022012 1.756303
8 022013 1.577855
9 022014 1.511905
10 022015 1.748879
11 032011 2.664336
12 032012 1.912023
13 032013 1.408602
14 032014 1.646091
15 032015 1.705069
16 042011 2.532895
17 042012 3.342926
18 042013 3.056657
"
ser_df <- read.table(text = Lines)
答案 1 :(得分:1)
以下是使用ggplot更明确地执行此操作的方法:
library(dplyr)
library(ggplot)
library(lubridate)
data %>%
mutate(date =
yearMon %>%
parse_date_time("%m%y"),
month =
date %>%
format("%B") %>%
ordered(month.name),
year =
date %>%
format("%Y") %>%
as.numeric) %>%
ggplot +
aes(x = year, y = V1, color = month) +
geom_line()