0

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

2 Answers 2

1

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)))
Sign up to request clarification or add additional context in comments.

Comments

0

Transform the data using pivot_longer or fortify from zoo package.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.