[英]Plot data frame's lists in ggplot2
I have a data.table / data frame with lists as values. 我有一个data.table /数据框,其中的列表作为值。 I would like to make a box or violin plot of the values, one violin/box representing one row of my data set, but I can't figure out how.
我想对这些值制作一个盒子或小提琴图,一个小提琴/盒子代表我的数据集的一行,但是我不知道怎么做。
Example: 例:
test.dt <- data.table(id = c('a','b','c'), v1 = list(c(1,0,10),1:5,3))
ggplot(data = test.dt, aes(x = as.factor(id), y = v1)) + geom_boxplot()
I get the following message: 我收到以下消息:
Warning message: Computation failed in
stat_boxplot()
: 'x' must be atomic警告消息:
stat_boxplot()
计算失败:“ x”必须是原子的
So my guess is that maybe I should split the lists of the values to rows somehow. 所以我的猜测是,也许我应该以某种方式将值列表拆分为行。 Ie: the row with a as id would be transformed to 3 rows (corresponding to the length of the vector in v1 ) with the same id, but the values would be split among them.
即: 与作为ID的行会被变换为3行(对应于V1的矢量的长度)具有相同id,但值将它们之间进行分割。
Firstly I don't know how to transform the data.table as mentioned, secondly I don't know either if this would be the solution at all. 首先,我不知道如何转换提到的data.table,其次,我也不知道这是否是解决方案。
Indeed, you need to unnest
your dataset before plotting: 实际上,在绘制之前,您需要
unnest
数据集:
library(tidyverse)
unnest(test.dt) %>%
ggplot(data = ., aes(x = as.factor(id), y = v1)) + geom_boxplot()
I believe what you are looking for is the very handy unnest()
function. 我相信您正在寻找的是非常方便的
unnest()
函数。 The following code works: 以下代码有效:
library(data.table)
library(tidyverse)
test.dt <- data.table(id = c('a','b','c'), v1 = list(c(1,0,10),1:5,3))
test.dt = test.dt %>% unnest()
ggplot(test.dt, aes(x = as.factor(id), y = v1)) +
geom_boxplot()
If you don't want to import the whole tidyverse, the unnest()
function is from the tidyr package. 如果您不想导入整个tidyverse,则
unnest()
函数来自tidyr包。
This is what unnest()
does with example data: 这是
unnest()
对示例数据的处理:
> data.table(id = c('a','b','c'), v1 = list(c(1,0,10),1:5,3))
id v1
1: a 1, 0,10
2: b 1,2,3,4,5
3: c 3
> data.table(id = c('a','b','c'), v1 = list(c(1,0,10),1:5,3)) %>% unnest()
id v1
1: a 1
2: a 0
3: a 10
4: b 1
5: b 2
6: b 3
7: b 4
8: b 5
9: c 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.