r - 箱线图(图形)与 bwplot(格子)中的公式表示法

标签 r lattice boxplot

自从我发布了对 this question 的回答以来,这一直困扰着我。昨天。

考虑以下数据:

carpaint <- data.frame(paint = c(rep(c("blue", "black", "red"), 
                                     times=3)),
                       car1 = c(100, 138, 123, 143, 112, 
                                144, 343, 112, 334), 
                       car2 = c(111, 238, 323, 541, 328, 
                                363, 411, 238, 313), 
                       car3 = c(432, 123, 322, 342, 323, 
                                522, 334, 311, 452))

如果我想按颜色生成箱线图(忽略按“汽车”进行的二次分组),我可以轻松使用 bwplot 中的公式符号来自lattice .

library(lattice)
bwplot(car1 + car2 + car3 ~ paint, data=carpaint)

Lattice Output

但是,要使用 boxplot 获得类似的图来自graphics ,公式表示法不同,所以我必须先将数据转换为长格式然后绘图,如下所示:

carpaint.l = reshape(carpaint, direction="long", varying=2:4, sep="")
boxplot(car ~ paint, data=carpaint.l)

Graphics Output

问题:有没有办法获得与 boxplot 相同的情节来自graphics不首先 reshape 数据,最好使用公式符号? (这忽略了这样一个事实,即这甚至可能不是链接问题的OP想要的输出类型——他们仍然没有对我的答案或@RomanLuštrik的问题发表评论。我只是想满足我的要求好奇心并学习更好地理解公式符号。)

Note: providing alternatives is definitely welcome, but I'm hoping that any answers also help me understand why some options are working and others are not. For instance, why does boxplot(as.matrix(carpaint[, 2:4]) ~ carpaint$paint) work but boxplot(carpaint[, 2:4] ~ carpaint$paint) does not. I find that strange because the documentation for boxplot has examples where they convert matrices to data frames before plotting even though it does not seem to be necessary.

最佳答案

carpaint[, 2:4] 是一个列表,而 cbind(car1, car2, car3)as.matrix(carpaint[, 2 :4]) 有一个底层的原子向量表示。箱线图的帮助页面表示“y”参数必须是数字向量。 boxplot.formula 使用 split:boxplot(split(mf[[response]], mf[-response]), ...)grp 参数被 split 回收以匹配响应向量的长度。 split 无法使用 list/data.frame 形式的三个向量来做到这一点。

关于r - 箱线图(图形)与 bwplot(格子)中的公式表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11521041/

相关文章:

r - 你如何删除 R 中的异常值?

python - 使用 matplotlib 的箱线图的奇怪形状

r - Shiny - FILL 值未在 Shiny 服务器中正确传递给 ggplot - 未找到错误对象 'input'

R:将数据帧 reshape 为 1's and 0' s 的矩阵

r - 如何在格子图中绘制刻度线

r - 类型为 'envir' 的参数无效 'character' -- 在带有晶格直方图的自定义函数中

r - ggplot::geom_boxplot() 如何更改 R 中一个框组的宽度

r - 向量化嵌套 for 循环,R

r - 加快R中的while循环

r - 使用 lattice 和 quantreg 绘制多分位数回归线