3

我想显示多个变量的箱线图,并按列按降序排列它们,就像在性能分析包中一样。我使用以下代码生成箱线图:

zx <- replicate (5, rnorm(50))
zx_means <- (colMeans(zx, na.rm = TRUE))
boxplot(zx, horizontal = FALSE, outline = FALSE)
points(zx_means, pch = 22, col = "darkgrey", lwd = 7)

到目前为止,我还没有想出一种方法来对它们进行如上所述的排名。我试过同时使用sortorder,但到目前为止没有任何令人满意的结果。

任何帮助将非常感激。

4

2 回答 2

3

order对我来说很好用!?:

colnames (zx) <- seq_len (ncol (zx))
boxplot(zx [, order (zx_means)], horizontal = FALSE, outline = FALSE)
points(zx_means [ order (zx_means)], pch = 22, col = "darkgrey", lwd = 7)
于 2012-03-26T12:45:31.683 回答
3

使用 ggplot2 这可以使用您的示例数据完成工作:

library(ggplot2)
library(reshape)

zx <- replicate (5, rnorm(50))

# ggplot2 uses long-shaped data.frame's, not matrices
zx_flat = melt(zx)[c(2,3)]
names(zx_flat) = c("cat","value")

# Here I calculate the mean per category
zx_flat = ddply(zx_flat, .(cat), mutate, mn = mean(value))
zx_flat = sort_df(zx_flat, "mn") # Order according to mean
# Here I manually set the order of the levels
# as this is the order ggplot2 uses
zx_flat$cat = factor(zx_flat$cat, levels = unique(zx_flat$mn))

# make the plot
ggplot(aes(factor(mn), value), data = zx_flat) + geom_boxplot()

我们得到:

在此处输入图像描述

于 2012-03-26T12:48:56.973 回答