R – ordering in boxplot

The following commands will create the ordering you need by rebuilding the Treatment and Species factors, with explicit manual ordering of the levels: mydata$Treatment = factor(mydata$Treatment,c(“L”,”M”,”H”)) mydata$Species = factor(mydata$Species,c(“G”,”R”,”B”)) edit 1 : oops I had set it to HML instead of LMH. fixing. edit 2 : what factor(X,Y) does: If you run factor(X,Y) on an … Read more

geom_boxplot with precomputed values

This works using ggplot2 version 0.9.1 (and R 2.15.0) library(ggplot2) DF <- data.frame(x=c(“A”,”B”), min=c(1,2), low=c(2,3), mid=c(3,4), top=c(4,5), max=c(5,6)) ggplot(DF, aes(x=x, ymin = min, lower = low, middle = mid, upper = top, ymax = max)) + geom_boxplot(stat = “identity”) See the “Using precomputed statistics” example here

How to change order of boxplots when using ggplot2?

Have you tried this: df2$variable <- factor(df2$variable, levels = c(‘vph.shr’,’vnu.shr’),ordered = TRUE) I just picked an ordering there, since my system is configured slightly differently than yours I suspect, so my ‘default ordering’ may differ. But you can just switch the position of levels when specifying them. A few other options, depend on your tastes: … Read more

How to add a number of observations per group and use group mean in ggplot2 boxplot?

Is this anything like what you’re after? With stat_summary, as requested: # function for number of observations give.n <- function(x){ return(c(y = median(x)*1.05, label = length(x))) # experiment with the multiplier to find the perfect position } # function for mean labels mean.n <- function(x){ return(c(y = median(x)*0.97, label = round(mean(x),2))) # experiment with the … Read more

Merge and Perfectly Align Histogram and Boxplot using ggplot2

You can use either egg, cowplot or patchwork packages to combine those two plots. See also this answer for more complex examples. library(dplyr) library(ggplot2) plt1 <- my_df %>% select(value) %>% ggplot(aes(x=””, y = value)) + geom_boxplot(fill = “lightblue”, color = “black”) + coord_flip() + theme_classic() + xlab(“”) + theme(axis.text.y=element_blank(), axis.ticks.y=element_blank()) plt2 <- my_df %>% select(id, … Read more

Changing whisker definition in geom_boxplot

geom_boxplot with stat_summary can do it: # define the summary function f <- function(x) { r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95)) names(r) <- c(“ymin”, “lower”, “middle”, “upper”, “ymax”) r } # sample data d <- data.frame(x=gl(2,50), y=rnorm(100)) # do it ggplot(d, aes(x, y)) + stat_summary(fun.data = f, geom=”boxplot”) # example with … Read more