在配对时间序列R上使用ggplot2 facet_grid

时间:2017-01-21 23:19:50

标签: r ggplot2 time-series

这里有一个ggplot2新手

我正在尝试使用ggplot2生成下面给出的样本数据的时间序列。以下简短代码没有给我我想要的东西。

    ggplot(dat,aes(x=year,y=data,fill=period,group=interaction(period, season))) +
  geom_line()+facet_grid(season ~ ., scales="free")

你可以看到线条显得很笨拙。如何为每个季节一起绘制cufured使用cu颜色,fu使用蓝色。

dat=structure(list(period = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("cu", "fu"), class = "factor"), 
        season = structure(c(2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 1L, 
        1L, 1L, 1L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 
        1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L), .Label = c("DJF", "JJA", 
        "MAM", "SON"), class = "factor"), month = structure(c(7L, 
        6L, 2L, 7L, 12L, 11L, 10L, 12L, 3L, 5L, 4L, 3L, 8L, 1L, 9L, 
        8L, 7L, 6L, 2L, 7L, 12L, 11L, 10L, 12L, 3L, 5L, 4L, 3L, 8L, 
        1L, 9L, 8L), .Label = c("april", "august", "dec", "feb", 
        "jan", "july", "june", "march", "may", "nov", "oct", "sep"
        ), class = "factor"), year = c(2001L, 2001L, 2001L, 2002L, 
        2001L, 2001L, 2001L, 2002L, 2001L, 2001L, 2001L, 2002L, 2001L, 
        2001L, 2001L, 2002L, 2001L, 2001L, 2001L, 2002L, 2001L, 2001L, 
        2001L, 2002L, 2001L, 2001L, 2001L, 2002L, 2001L, 2001L, 2001L, 
        2002L), data = c(84.08969137, 76.4948428, 18.35492802, 101.8821712, 
        24.21773903, 16.44881361, 19.57283027, 48.27623315, 8.572824549, 
        12.97601394, 11.50496081, 15.14899058, 13.96396375, 27.21030149, 
        36.1606234, 23.35430348, 95.77643784, 94.84972642, 47.26900009, 
        2.385978093, 21.48062239, 24.67779645, 20.07044416, 43.09234771, 
        13.28295078, 19.27189857, 15.24661793, 21.75991334, 19.38239851, 
        39.93109491, 38.54500325, 33.77559647)), .Names = c("period", 
    "season", "month", "year", "data"), class = "data.frame", row.names = c(NA, 
    -32L))

感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

我会做类似的事情:

library(ggplot2)
ggplot(dat,aes(x=
                 as.Date(sprintf("%s-%s-01",year,month),
                         "%Y-%b-%d"),

                         y=data,group=period,color=period)) +
  geom_line()+facet_grid(season ~ ., scales="free") +
  xlab("time")

事实上,我正在创建一个常规日期并按周期分组。

enter image description here