简体   繁体   中英

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 (eg 1:75 ) and y-axis is the matrix value (eg sin(1:75) ).

在此输入图像描述 ( 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"

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")

在此输入图像描述

Explanation: We first convert all matrices to data.frame s 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() .

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

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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM