如何在 R 中的同一图上绘制元组层?

How to plot layers of tupples on same plot in R?

我正在尝试在同一地块上绘制每个区域的时间和 NDVI。我认为要做到这一点,我必须将日期列从字符转换为时间,然后绘制每一层。但是我不知道该怎么做。有什么想法吗?

list(structure(list(observation = 1L, HRpcode = NA_character_, 
    timeseries = NA_character_), row.names = c(NA, -1L), class = c("tbl_df", 
"tbl", "data.frame")), structure(list(observation = 1:6, time = c("2014-01-01", 
"2014-02-01", "2014-03-01", "2014-04-01", "2014-05-01", "2014-06-01"
), ` NDVI` = c("0.3793765496776215", "0.21686891782421552", "0.3785652933528299", 
"0.41027240624704164", "0.4035578030242673", "0.341299793064468"
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
)), structure(list(observation = 1:6, time = c("2014-01-01", 
"2014-02-01", "2014-03-01", "2014-04-01", "2014-05-01", "2014-06-01"
), ` NDVI` = c("0.4071076986818826", "0.09090719657570319", "0.35214166081795284", 
"0.4444311032927228", "0.5220702877666005", "0.5732370503295022"
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
)), structure(list(observation = 1:6, time = c("2014-01-01", 
"2014-02-01", "2014-03-01", "2014-04-01", "2014-05-01", "2014-06-01"
), ` NDVI` = c("0.3412131556625801", "0.18815996897460135", "0.5218904976415136", 
"0.6970128777711452", "0.7229657162729096", "0.535967435470161"
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
)))
111

这是一种使用 lubridate 处理日期和 dplyr 使 data.frames 的绑定更容易理解的方法。

请注意,组名取自列表名称,由于您提供的数据中不存在,我们必须提前设置。

library(lubridate)
library(ggplot2)
library(dplyr)
names(data) <- 1:3
data <- bind_rows(data, .id = "group")
data$time <- ymd(data$time)
setnames(data," NDVI","NDVI")
data$NDVI <- as.numeric(data$NDVI)
ggplot(data, aes(x=time,y=NDVI,color=Group)) + geom_line()

首先我们需要清理您的数据。此列表中的第一个元素为空

df = df[-1]

现在我们需要做一个data.frame

df = do.call(rbind, df)

我要添加一个 region 变量,更改 NDVI 的名称以删除 space, 将 ndvi 更改为数值向量,并将 time 更改为 Date 对象

library(dplyr)
df = df %>% 
  mutate(region = factor(rep(1:3, rep(6, 3)))) %>% 
  rename(ndvi = ' NDVI') %>% 
  mutate(ndvi = as.numeric(ndvi)) %>% 
  mutate(time = as.Date(time))

现在我们可以使用ggplot2按区域绘制数据

library(ggplot2)
g = df %>% 
  ggplot(aes(x = time, y = ndvi, col = region)) +
  geom_line()
g

给出了这个情节: