箱形图按平均值排列

时间:2012-03-26 11:16:24

标签: r ggplot2 boxplot

我想显示多个变量的箱图,并按列降序排列,就像在 Performance Analytics 包中一样。我使用以下代码生成箱图:

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)

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

非常感谢任何帮助。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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()

我们得到:

enter image description here

相关问题