对于多个时间序列的 ggplot 循环即

For loop in ggplot for multiple time series viz

我需要为我的数据集中的每个时间序列(列)绘制多个单独的图:

https://github.com/rhozon/datasets/raw/master/multiple_time_series_dataset.csv

我想到了一些 for 循环,循环遍历每一列并单独绘制每个图形。

ggplot(df, aes(x = timestamp, 
               y = for loop for each column) ) +
geom_line()

如何通过为数据集的每一列生成时间图来节省时间?

也许这就是您要找的

library(tidyverse)
library(lubridate)
library(plotly)
df <- vroom::vroom("https://github.com/rhozon/datasets/raw/master/multiple_time_series_dataset.csv")

df <- df %>% 
  mutate(timestamp = dmy(timestamp))

VARS <- names(df)[-1][1:3]         

map(.x = VARS,
    .f = ~ ggplot(df, aes(x = timestamp, y = .data[[.x]])) +
      geom_line()) %>%
  map(ggplotly)

您可以尝试使用 lapply 而不是 for 循环来执行以下代码。

# transforming timestamp in date object
df$timestamp <- as.Date(df$timestamp, format = "%d/%m/%Y")
# create function that is used in lapply
plotlines <- function(variables){
  ggplot(df, aes(x = timestamp, y = variables)) +
  geom_line() 
}
# plot all plots with lapply
plots <- lapply(df[names(df) != "timestamp"], plotlines) # all colums except timestamp
plots