jane
jane

Reputation: 567

Plot data from list using ggplot2

I have a list of 4 different matrix length. I wish to plot them as set of time series like in the example below just that x-axis is a running number (e.g. 1:75) and y-axis is the matrix value (e.g. sin(1:75)).

enter image description here (https://homepage.divms.uiowa.edu/~luke/classes/STAT4580/timeseries_files/figure-html/unnamed-chunk-39-2.png).

I know that that ggplot2 does not handle lists so any idea how to advance?

Script:

mat1 <- matrix(cos(1:50), nrow = 50, ncol = 1)
mat2 <- matrix(sin(1:75), nrow = 75, ncol = 1)
mat3 <- matrix(tan(1:50), nrow = 50, ncol = 1)
mat4 <- matrix(1:100, nrow = 100, ncol = 1)
myList <- list(mat1, mat2, mat3, mat4)

names(myList)[1] <- "mat1"
names(myList)[2] <- "mat2"
names(myList)[3] <- "mat3"
names(myList)[4] <- "mat4"

Upvotes: 3

Views: 259

Answers (2)

Maurits Evers
Maurits Evers

Reputation: 50728

Something like this?

library(tidyverse)
map_dfr(myList, ~as.data.frame(.x), .id = "id") %>%
    group_by(id) %>%
    mutate(n = 1:n()) %>%
    ungroup() %>%
    mutate(id = as.factor(id)) %>%
    ggplot(aes(n, V1, colour = id)) +
    geom_line() +
    facet_wrap(~ id, scales = "free")

enter image description here

Explanation: We first convert all matrices to data.frames and bind all rows together into a single data.frame including an id which derives from the list names; we can then number rows by id and then plot the row number vs. the single column.


Here is the same code "un-piped" and "uglified"

library(tidyverse)

# Convert from list of matrices to long data.frame
df.long <- map_dfr(myList, ~as.data.frame(.x), .id = "id")

# Group by id
df.long <- group_by(df.long, id)

# Add row number (per group)
df.long <- mutate(df.long, n = 1:n())

# ungroup
df.long <- ungroup(df.long)

# Make sure id is a factor
df.long <- mutate(df.long, id = as.factor(id))

# (gg)plot
ggplot(df.long, aes(n, V1, colour = id)) +
    geom_line() +
    facet_wrap(~ id, scales = "free")

It's easy to see how %>% takes the left object and uses it as the first argument of the function on the right; so f(x) would become x %>% f().

Upvotes: 3

Jon Spring
Jon Spring

Reputation: 66890

library(tidyverse)
enframe(myList) %>%
  unnest() %>%
  group_by(name) %>%
  rowid_to_column() %>%
  ungroup() %>%

  ggplot(aes(rowid, value)) + 
  geom_line() + 
  facet_wrap(~name, scales = "free")

enter image description here

Upvotes: 2

Related Questions