'Plot list of lists with facet_wrap()
Say I have a list of the following structure:
> results %>% str()
List of 6
$ : num [1:5000, 1:2] -9.22 10.01 -3.33 -3.91 1.2 ...
..- attr(*, "scaled:center")= num [1:2] -0.1 -0.05
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:5000] "1" "2" "3" "4" ...
.. ..$ : NULL
$ : num [1:5000, 1:2] -7.82 7.74 6.30 -2.34 -5.76 ...
..- attr(*, "scaled:center")= num [1:2] 0.1 0.5
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:5000] "1" "2" "3" "4" ...
.. ..$ : NULL
$ : num [1:5000, 1:2] 1.87 0.17 -3.90 -0.20 4.73 ...
..- attr(*, "scaled:center")= num [1:2] -0.3 -0.001
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:5000] "1" "2" "3" "4" ...
.. ..$ : NULL
$ : num [1:5000, 1:2] -2.54 8.29 -4.76 -4.47 4.59 ...
..- attr(*, "scaled:center")= num [1:2] 2.05 -0.03
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:5000] "1" "2" "3" "4" ...
.. ..$ : NULL
$ : num [1:5000, 1:2] --1.67 0.74 -4.94 9.94 -1.70 ...
..- attr(*, "scaled:center")= num [1:2] -0.3 -0.5
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:5000] "1" "2" "3" "4" ...
.. ..$ : NULL
$ : num [1:5000, 1:2] 8.91 -7.83 8.12 6.32 0.84 ...
..- attr(*, "scaled:center")= num [1:2] 3.01 0.8
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:5000] "1" "2" "3" "4" ...
.. ..$ : NULL
I want to plot each list in ggplot and can do this easily by referencing the correct index and feeding it into a ggplot() call. For example:
results[[1]] %>%
as.data.frame() %>%
ggplot(., aes(V1, V2, color = color, alpha = color)) +
geom_point() +
scale_color_gradientn(colours = viridisLite::turbo(256)) +
labs(title = "nn = ")
But this becomes rather tedious when I want a plot for each list. Ideally i'd use something like facet_wrap() to produce a single graph with all the plots in it. However, I do not know how to transform the original results object into the right format. I have tried the following:
results %>% as.data.frame() %>% dim()
But that returns a df of 5,000 x 12, whereas what I want is a df of 30,000 x 3 (where the third column is the indicator for which list the data originally comes from).
Does anyone know if there is an easy way to feed the lists into ggplot directly and facet them as per the description above? Or, alternatively, can someone help me figure out how to transform the results object into the right format?
Many thanks in advance
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
