Lucia - 1 month ago 6x
R Question

# Plot a list contains many lists with R

I have a list like this, the number above \$

`1081786081`
is the user id, I want to plot the day_count according to time.

It's easy to do that if it's a data frame

``````plot(list4\$day_count)
``````

But I don't know how to do it for each list.Should I use lapply?

``````\$`1081786081`
time day_count
1  2016-01-13         2
2  2016-01-20         2
3  2016-02-06         2
4  2016-02-23         2
5  2016-03-14         2
6  2016-03-24         2
7  2016-04-06         2
8  2016-04-11         2
9  2016-05-04         2
10 2016-06-06         2
11 2016-06-26         2
12 2016-07-01         2

\$`1087949661`
time day_count
1  2016-01-02         4
2  2016-01-11         2
3  2016-01-20         2
4  2016-01-21         6
5  2016-01-22         2
6  2016-01-27         4
7  2016-01-30         4
8  2016-02-02         2
9  2016-02-05         2
``````

If we need to plot the `list` of `data.frame`s in a single `pdf` with separate pages for each plot, after setting the output `.pdf`, we loop through the 'list4', and `plot`.

``````pdf("yourplot.pdf")
invisible(lapply(list4, function(x) with(x, plot(time, day_count))))
dev.off()
``````

We can also create some identifier for each `plot` by looping through the `names` of the `list` elements

``````pdf("yourplot.pdf")
invisible(lapply(names(list4), function(nm) with(list4[[nm]],
plot(time, day_count, main = paste("plot of", nm)))))
dev.off()
``````

If we need a single plot with lines, we can `rbind` the `list` elements and then do the `plot`ting.

``````library(dplyr)
library(ggplot2)
bind_rows(list4, .id = "grp") %>%
ggplot(., aes(x=time, y = day_count, colour = grp)) +
geom_line() +
geom_point()
``````

### data

``````list4 <- structure(list(`1081786081` = structure(list(time = structure(c(16813,
16820, 16837, 16854, 16874, 16884, 16897, 16902, 16925, 16958,
16978, 16983), class = "Date"), day_count = c(2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L)), .Names = c("time", "day_count"
), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9",
"10", "11", "12"), class = "data.frame"), `1087949661` = structure(list(
time = structure(c(16802, 16811, 16820, 16821, 16822, 16827,
16830, 16833, 16836), class = "Date"), day_count = c(4L,
2L, 2L, 6L, 2L, 4L, 4L, 2L, 2L)), .Names = c("time", "day_count"
), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9"),
class = "data.frame")), .Names = c("1081786081",
"1087949661"))
``````
Source (Stackoverflow)