Search code examples
rggplot2time-seriesdata-visualizationgplots

For loop in ggplot for multiple time series viz


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 ?


Solution

  • 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