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?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With