如何将列表传递给ggplot2? [英] How to pass a list to ggplot2?
问题描述
我试图在ggplot2上做一个值列表的boxplot,但问题是它不知道如何处理列表,我该怎么办?
$ b例如:
k < - list(c(1,2,3,4,5), c(1,2,3,4),c(1,3,6,8,14),c(1,3,7,8,10,37))
k
[[1 ]]
[1] 1 2 3 4 5
[[2]]
[1] 1 2 3 4
[[3] ]
[1] 1 3 6 8 14
[[4]]
[1] 1 3 7 8 10 37
如果我将 k
作为参数传递给 boxplot() code>它将完美地处理它,并产生一个很好的(不太好用的... hehehe)boxplot,其中所有值的范围都以Y轴和列表索引(每个元素)作为X轴。
我应该如何用ggplot2达到完全相同的效果?我认为数据框或矩阵不是一个选项,因为这些矢量长度不同。
谢谢
答案是,你没有。 ggplot2
设计用于处理数据帧,特别是长表格数据帧。这意味着您需要将数据作为一个高维向量,并且具有分组因子:
d < - data.frame(x = unlist(k),
grp = rep(letters [1:length(k)],times = sapply(k,length)))
ggplot(d,aes(x = grp,y = x ))+ geom_boxplot()
正如评论中指出的那样, melt
达到与本手册重塑相同的效果并且更简单。我想我喜欢刁难。
I'm trying to do a boxplot of a list of values at ggplot2, but the problem is that it doesn't know how to deal with lists, what should I try ?
E.g.:
k <- list(c(1,2,3,4,5),c(1,2,3,4),c(1,3,6,8,14),c(1,3,7,8,10,37))
k
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] 1 2 3 4
[[3]]
[1] 1 3 6 8 14
[[4]]
[1] 1 3 7 8 10 37
If I pass k
as an argument to boxplot()
it will handle it flawlessly and produce a nice (well not so nice... hehehe) boxplot with the range of all the values as the Y-axis and the list index (each element) as the X-axis.
How should I achieve the exact same effect with ggplot2 ? I think that dataframes or matrices are not an option because the vectors are of different length.
Thanks
The answer is that you don't. ggplot2
is designed to work with data frames, particularly long form data frames. That means you need your data as one tall vector, with a grouping factor:
d <- data.frame(x = unlist(k),
grp = rep(letters[1:length(k)],times = sapply(k,length)))
ggplot(d,aes(x = grp, y = x)) + geom_boxplot()
And as pointed out in the comments, melt
achieves the same result as this manual reshaping and is much simpler. I guess I like to make things difficult.
这篇关于如何将列表传递给ggplot2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!