时间序列从一个地块中的三年

时间:2018-02-08 09:47:31

标签: r plot ggplot2 time-series

我正在努力(由于缺乏知识和经验)在R中用三个不同年份(2009年,2013年和2017年)的时间序列创建一个情节。通过在线搜索未能解决这个问题,这使我在这里。

我希望创建一个图表,显示所有年份5月至10月期间硝酸盐浓度的变化,但由于x轴由一个特定年份定义,因此保持失败。我也收到错误,因为x轴长度不同(由于样本数量不同)。为了解决这个问题,我尝试过为月份和年份制作单独的专栏,但没有成功。

数据示例:

date        NO3.mg.l     year    month
2009-04-22  1.057495     2009     4
2013-05-08  1.936000     2013     5
2017-05-02  2.608000     2017     5

代码:

ggplot(nitrat.all, aes(x = date, y = NO3.mg.l, colour = year)) + geom_line()

此代码生成一个图表,其中线条彼此相邻,而我想要一个彼此重叠的图表。任何帮助将不胜感激。

Nitrate plot

1 个答案:

答案 0 :(得分:0)

对于密谋

,这可能会有所帮助
   // root_layout is the relative layout 
   final RelativeLayout layout = findViewById(R.id.root_layout);

    findViewById(R.id.test_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RelativeLayout.LayoutParams[] params = new RelativeLayout.LayoutParams[4];
            EditText[] dynamicEditText = new EditText[4];
            for (int i = 1; i < 4; i++) {
                params[i] = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

                dynamicEditText[i] = new EditText(MainActivity.this);
                dynamicEditText[i].setId(i);
                dynamicEditText[i].setText("Edit Text "+i);
                if (i > 1) {
                    params[i].addRule(RelativeLayout.BELOW, dynamicEditText[i - 1].getId());
                }
                dynamicEditText[i].setLayoutParams(params[i]);
                layout.addView(dynamicEditText[i]);


            }

        }
    });
}

对于选择与某个月对应的日期,您可以使用基本R函数按条件对数据框进行子集化:

library("lubridate")
library("ggplot2")
# evample of data with some points for each year
nitrat.all <- data.frame(date = c(ymd("2009-03-21"), ymd("2009-04-22"), ymd("2009-05-27"),
    ymd("2010-03-15"), ymd("2010-04-17"), ymd("2010-05-10")), NO3.mg.l = c(1.057495, 1.936000, 2.608000,
        3.157495, 2.336000, 3.908000))
nitrat.all$year <- format(nitrat.all$date, format = "%Y")
ggplot(data = nitrat.all) +
    geom_point(mapping = aes(x = format(date, format = "%m-%d"), y = NO3.mg.l, group = year, colour = year)) +
    geom_line(mapping = aes(x = format(date, format = "%m-%d"), y = NO3.mg.l, group = year, colour = year))

另一个非常优雅的方法是使用n_month1 <- 3 # an index of the first month of the period to select n_month2 <- 4 # an index of the first month of the period to select test_for_month <- (as.numeric(format(nitrat.all$date, format = "%m")) >= n_month1) & (as.numeric(format(nitrat.all$date, format = "%m")) <= n_month2) nitrat_to_plot <- nitrat.all[test_for_month, ]

中的filter()
dplyr