Grouped horizontal boxplot with bwplot

折月煮酒 提交于 2020-01-03 16:49:09

问题


I have the following code that allows grouped vertical box-plots via the bwplot function in lattice. Reproducible example..

data(mpg, package = "ggplot2") 

bwplot( hwy~class, data = mpg, groups = year,
    pch = "|", box.width = 1/3,
    auto.key = list(points = FALSE, rectangles = TRUE, space = "right"),
    panel = panel.superpose,
    panel.groups = function(x, y, ..., group.number) {
        panel.bwplot(x + (group.number-1.5)/3, y, ...)
     })

This works fine, but I would like the boxplots to be horizontal, so I changed the first line, keeping everything else equal:

bwplot( class~hwy, data = mpg, groups = year, ...

But the graph comes out like this

. I have tried playing around with the code without success. I have 2 questions: Firstly, how can I, or is it possible to have the boxplots not superimposed on each other? And secondly and more generally, how can I set the color panel to grayscale, so the plot come out in shades of gray or just black and white?

回答1:


If it's not critical that you use bwplot, you may try ggplot:

ggplot(data = mpg, aes(x = class, y = hwy, fill = factor(year))) +
  geom_boxplot() +
  coord_flip() +
  scale_fill_grey(start = 0.5, end = 0.8) +
  theme_classic()




回答2:


  • You should also invert x and y roles in panel.groups function.
  • Use trellis.par.set to change fill color of superposed symbol

data(mpg, package = "ggplot2") 
library(latticeExtra)
mycolors <- grey.colors(5, start = 0.1, end = 0.9)
trellis.par.set(superpose.symbol = list(fill = mycolors,col=mycolors))
bwplot(class~hwy, data = mpg, groups = year,
                pch = "|", box.width = 1/3,
                panel = panel.superpose,
                panel.groups = function(x, y,..., group.number) 
                    panel.bwplot(x,y + (group.number-1.5)/3,...)
            ) 

But it is probably easier here to use the ggplot2 solution.



来源:https://stackoverflow.com/questions/20172560/grouped-horizontal-boxplot-with-bwplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!