Home > database >  Boxplot with median value label and table of n below
Boxplot with median value label and table of n below

Time:10-19

I like to create a boxplot with median labels and a summary table of median and n (number of observations in each group) at the bottom and y-axis labels rotated 90 degrees.

This is my test dataset

exampledf <- data.frame( val=c(4, 2, 3, 5, 4, 1, 5, 8), 
                         let=c("a", "a", "a", "b", "b", "c", "c", "c") )

I can do this

boxplot(val ~ let, data = exampledf)

Not sure how to rotate the y-axis label 90, add median values and table of n below. Expected figure

enter image description here

CodePudding user response:

We can use the invisible output of boxplot to get medians and ns. For the median labels and table-like object below the panel, we can use text and mtext functions as well as lines. Best we use the png device.

png('myplot.png', 600, 400)

par(mar=c(7, 4, 4, 2) .1)

b <- boxplot(val ~ let, data=exampledf, xlab='', las=1)
mds <- b$stats[3, ]
text(1:3, mds   .225, labels=formatC(mds,format='f', digits=2), cex=.8)
mtext(c('n', b$n), 1, 2.5, at=c(.5, 1:3)-.05, adj=0)
mtext(c('median', formatC(mds,format='f', digits=2)), 1, 3.5, at=c(.5, 1:3)-.05, adj=0)
lines(c(.75, 3.25), c(-.25, -.25), xpd=TRUE)
lines(c(.75, 3.25), c(-1.5, -1.5), xpd=TRUE)
mtext('let', line=1)

dev.off()

enter image description here

  • Related