I want to plot boxplots showing the 95 percentile instead of the IQR, including outliers as defined by exceeding the 95% criterion. This code is working fine, and based on several answers found here and on the web:
f1 <- function(x) {
subset(x, x < quantile(x, probs=0.025)) # only for low outliers
}
f2 <- function(x) {
r <- quantile(x, probs = c(0.025, 0.25, 0.5, 0.75, 0.975))
names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
r
}
d <- data.frame(x=gl(2,50), y=rnorm(100))
library(ggplot2)
p0 <- ggplot(d, aes(x,y)) +
stat_summary(fun.data = f2, geom="boxplot") + coord_flip()
p1 <- p0 + stat_summary(fun.y = f1, geom="point")
The structure of d is:
'data.frame': 100 obs. of 2 variables:
$ x: Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 1 1 1 ...
$ y: num 2.275 0.659 -0.821 -0.129 1.997 ...
Now, coming to my real data, which is structured essentially the same:
str(test)
'data.frame': 11830917 obs. of 2 variables:
$ x: Ord.factor w/ 34 levels "SG26"<"SG22"<..: 18 18 18 18 18 18 18 18 18 18 ...
$ y: num 84.6 84.1 93.3 84 93.2 94.3 83.3 92.5 94.5 98.8 ...
Now, if i am applying the same plot command, i get:
p0 <- ggplot(test, aes(x,y)) + stat_summary(fun.data = f2, geom="boxplot") + coord_flip()
p1 <- p0 + stat_summary(fun.y = f1, geom="point")
p1
Warning message:
Computation failed in `stat_summary()`:
Argumente implizieren unterschiedliche Anzahl Zeilen: 1, 0
The final line is the german version of "arguments imply differing number of rows 1 0". p0 is produced just fine.
What could be the difference between the two datasets?
The problem, as identified by @Heroka and @bdemarest, arose by one factor level having only one value.
My workaround is to skip those factors:
f1 <- function(x) {
if (length(x) > 7) {
return(subset(x, x < quantile(x, probs=0.025))) # only for low outliers
} else {
return(NA)
}
}
For unknown reasons, the problem persisted until there were at least 7 values per factor level.
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