Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a list to ggplot2?

Tags:

r

ggplot2

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

like image 648
Lianzinho Avatar asked Dec 08 '11 00:12

Lianzinho


1 Answers

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

enter image description here

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.

like image 195
joran Avatar answered Oct 05 '22 02:10

joran