Home > OS >  For loop in ggplot for multiple time series viz
For loop in ggplot for multiple time series viz

Time:12-11

I need to make multiple individual plots of each time series (column) in my dataset:

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

I thought of some for loop that loops through each column and plots each graph individually.

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

How could I save my time by generating a time graph for each column of my dataset ?

CodePudding user response:

You could try following code using lapply instead of for loop.

# 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

CodePudding user response:

Maybe that's what you're looking for

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)
  • Related