如何使用矩阵在ggplot中生成箱线图

时间:2010-02-25 22:42:29

标签: r ggplot2

在R中,很容易将矩阵变成箱线图

> myMatrix
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]   27   32   31   28   20   28   10   29   15    29
 [2,]   31   33   20   28   21    9   14   21   34    33
 [3,]   27   33   28   23   26   33   19   11   26    30
 [4,]   33   17   10   31   10   32   10   29   31    28
 [5,]   25   10   29   34   32   33   28   32   32    32
 [6,]   32   19   13   32   26   20    9   26   32    33
 [7,]   33   32   18   26   27   28   29   32   24    25
 [8,]   33   34   32   30   27   31   22   32   33    30
 [9,]   32   34   31   22   17   31   11   27   18    23
[10,]   26   10   30   30   27    4    4    4    4     4

> boxplot(as.data.frame(myMatrix))

如何在ggplot中完成同样的事情?

1 个答案:

答案 0 :(得分:8)

您可以使用melt()函数,然后使用geom_boxplot()。 首先重现数据(感谢Excel):

vec <- c(c(27, 32, 31, 28, 20, 28, 10, 29, 15, 29), 
 + c(31, 33, 20, 28, 21,  9, 14, 21, 34, 33), 
 + c(27, 33, 28, 23, 26, 33, 19, 11, 26, 30), 
 + c(33, 17, 10, 31, 10, 32, 10, 29, 31, 28), 
 + c(25, 10, 29, 34, 32, 33, 28, 32, 32, 32), 
 + c(32, 19, 13, 32, 26, 20,  9, 26, 32, 33), 
 + c(33, 32, 18, 26, 27, 28, 29, 32, 24, 25), 
 + c(33, 34, 32, 30, 27, 31, 22, 32, 33, 30), 
 + c(32, 34, 31, 22, 17, 31, 11, 27, 18, 23), 
 + c(26, 10, 30, 30, 27,  4,  4,  4,  4,  4))
myMatrix <- matrix(data=vec, ncol=10, byrow=TRUE)

然后融化并绘制:

library(reshape)
library(ggplot2)
ggplot(data=melt(as.data.frame(myMatrix)), aes(variable, value)) + geom_boxplot()

另外,正如Hadley(很久以前)在评论中所建议的那样,没有必要将矩阵转换为数据框:

ggplot(data=melt(myMatrix), aes(as.factor(X2), value)) + geom_boxplot()