Milaa
Milaa

Reputation: 419

How to plot a list with multiple data frames in one graph using ggplot in R

In the following list, there are several data frames representing time series of some variable:

list.data <- list(data.frame(x=c(1:10), y=rnorm(10)),data.frame(x=c(11:20), y=rnorm(10)))

How can I plot these time series in one graph using ggplot by looping without the need of making the entry manually. when I tried using lapply each time series has been plotted in a different graph.

lapply(list.data, function(z){ggplot()+geom_line(data=z, aes(x, y))})

manually plot is tedious as I have so many items on the list

ggplot()+geom_line(data=list.data[[1]], aes(x, y))+
         geom_line(data=list.data[[2]], aes(x, y), col='red')

Is there any easy way to plot without repeating geom_line several times

Upvotes: 0

Views: 692

Answers (2)

markus
markus

Reputation: 26343

You can add a list to ggplot()

library(ggplot2)
ggplot() + 
  lapply(list.data, function(z) geom_line(data = z, aes(x, y)))

enter image description here


Given OP's example data, we could first rbind the data, and then plot

ggplot(data = do.call(rbind, list.data)) + 
  geom_line(aes(x, y))

Data

set.seed(42)
list.data <- list(data.frame(x=c(1:10), y=rnorm(10)),data.frame(x=c(11:20), y=rnorm(10)))

Upvotes: 1

Nithin .M
Nithin .M

Reputation: 85

Transform the data using pivot_longer or fortify from zoo package.

Upvotes: 0

Related Questions