Getting an error that ggplot2_3.2.0 can't draw more than one boxplot per group

你。 提交于 2021-01-27 06:19:08

问题


I have xy data that I'd like to plot using R's ggplot:

library(dplyr)
library(ggplot2)
set.seed(1)

df <- data.frame(group = unlist(lapply(LETTERS[1:5],function(l) rep(l,5))),
                 x = rep(1:5,5),
                 y = rnorm(25,2,1),
                 y.se = runif(25,0,0.1)) %>%
  dplyr::mutate(y.min = y-3*y.se,
                y.low = y-y.se,
                y.high = y+y.se,
                y.max = y+3*y.se)

As you can see, while df$x is a point (integer), df$y has an associated error, which I would like to include using a box plot.

So my purpose is to plot each row in df by its x coordinate, using y.min, y.low, y, y.high, and y.max to construct a boxplot, and color and fill it by group. That means, that I'd like to have each row in df, plotted as a box along a separate x-axis location and faceted by df$group, such that df$group A's five replicates appear first, then to their right df$group B's replicates, and so on.

This code used to work for my purpose until I just installed the latest ggplot2 package (ggplot2_3.2.0):

ggplot(df,aes(x=x,ymin=y.min,lower=y.low,middle=y,upper=y.high,ymax=y.max,col=group,fill=group))+
geom_boxplot(position=position_dodge(width=0),alpha=0.5,stat="identity")+
facet_grid(~group,scales="free_x")+scale_x_continuous(breaks = integerBreaks())

Now I'm getting this error:

Error: Can't draw more than one boxplot per group. Did you forget aes(group = ...)?

Any idea?


回答1:


You need a separate boxplot for each combination of x and group, so you can set the group aesthetic to interaction(x, group):

ggplot(df,aes(x=x,ymin=y.min,lower=y.low,middle=y,upper=y.high,
              ymax=y.max,col=group,fill=group))+
    geom_boxplot(aes(group = interaction(x, group)), 
                 position=position_dodge(width=0),
                 alpha=0.5,stat="identity")



回答2:


This code used to work for my purpose until I just installed the latest ggplot2 package (ggplot2_3.2.0)

You are right: I just experienced a similar error with a code I recently wrote using ggplot2 boxplots, and just find out this new error related to ggplot2 latest update. As Marius already pointed out, specifying the group in the aes() did solve the problem for me also. However I don't understand the rest of his answer, as it is not providing the faceting...

Here is a working solution with facet_grid(), you were close:

ggplot(df,aes(x=x,ymin=y.min,lower=y.low,middle=y,upper=y.high,ymax=y.max,col=group,fill=group, group=x))+
geom_boxplot(position=position_dodge(width=0),alpha=0.5,stat="identity")+
facet_grid(~group,scales="free_x")



来源:https://stackoverflow.com/questions/57192727/getting-an-error-that-ggplot2-3-2-0-cant-draw-more-than-one-boxplot-per-group

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