Nithin .M
Nithin .M

Reputation: 85

Plotting multiple graphs from a list

I have a time series data from 1990 to 1994 of 5 variables in 15 sheets. I read all these data to a list. I need to do a time series plot of all the 5 Variables for 15 companies in multiple graphs. How can this be done? I mean I basically need 5 figures each containing the time series plot of 15 companies of the respective variables.

Upvotes: 1

Views: 838

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76651

With package ggplot2 this can be done as follows. I assume you have a list of 15 dataframes named df_list.

First, rbind them together with the name of the company as a new column. The companies' names are in this fake data case stored as the df's names.

all_df <- lapply(names(df_list), function(x){
  DF <- df_list[[x]]
  DF$Company <- x
  DF
})
all_df <- do.call(rbind, all_df)

Then, reshape from wide to long format.

long_df <- reshape2::melt(all_df, id.vars = c("Company", "Date"))

Now, plot them. The graphs can be customized at will, there are many posts on it.

library(ggplot2)

ggplot(long_df, aes(x = Date, y = value, colour = Company)) +
  geom_line() +
  facet_wrap(~ variable)

enter image description here

Data creation code.

set.seed(1234)

Dates <- seq(as.Date("1990-01-01"), as.Date("1994-12-31"), by = "month")
n <- length(Dates)
df_list <- lapply(1:15, function(i){
  tmp <- matrix(rnorm(5*n), ncol = 5)
  tmp <- apply(tmp, 2, cumsum)
  colnames(tmp) <- paste0("Var", 1:5)
  tmp <- as.data.frame(tmp)
  tmp$Date <- Dates
  tmp
})
names(df_list) <- paste("Company", seq_along(df_list), sep = ".")

Upvotes: 1

Related Questions