Consistently shading row in addtable2plot - plotrix
Question
I'm regularly generating histograms from simulated data, and find it quite helpful to attach an associated decile table for the data. I've been doing this with the addtable2plot function from plotrix. I also find it useful to highlight the row in the table which contains the 50% value - here is an example:
library(plotrix)
# Generate data
mu <- -1.771957
sd <- 0.4716474
foo <- rlnorm(100000, mu, sd)
# Generate decile table
xmax <- .75
max <- format(xmax, digits=2, nsmall=2)
dc <- quantile(foo, probs=seq(0, 1, 0.1))
dps <- c("100%", "90%", "80%", "70%", "60%", "50%", "40%", "30%", "20%", "10%", "0%")
dc <- format(round(dc, digits=2), nsmall=2)
decile <- as.data.frame(dps)
deciles <- as.data.frame(cbind(dps,dc), row.names=FALSE)
colnames(deciles) <- c("Probability", "Rate")
deciles$"Rate" <- as.character(deciles$"Rate")
deciles[1,2] <- "0.00"
deciles[11,2] <- paste(">", max, sep="")
# create a plot
hist(foo, freq=F, xlim=c(0,xmax), breaks=50, col="blue")
top <- max(axis(2))
rect(xleft=(.69*xmax), xright=(1.04*xmax), ybottom=(.615*top), ytop=(.665*top), col="gray91", border=NA)
addtable2plot(x=(1.04*xmax), y=(top), xjust=1, yjust=0, table=deciles, cex=0.82,
title="Title", hlines=TRUE, vlines=TRUE, bty="o", lwd=1.5, bg="transparent")
As you can see, I've been shading simply by adding a colored rectangle underneath the table plot. This takes a lot of tweaking on the xleft, ybottom, and ytop parameters for each histogram.
Is there any way to consistently do this highlighting without all the hassle? Thanks,
Solution
You mean like this, maybe:
bg_col <- matrix("white",nrow(deciles),ncol(deciles))
bg_col[11,] <- "grey"
# create a plot
hist(foo, freq=F, xlim=c(0,xmax), breaks=50, col="blue")
top <- max(axis(2))
rect(xleft=(.69*xmax), xright=(1.04*xmax), ybottom=(.615*top), ytop=(.665*top), col="gray91", border=NA)
addtable2plot(x=(1.04*xmax), y=(top), xjust=1, yjust=0, table=deciles, cex=0.82,
title="Title", hlines=TRUE, vlines=TRUE, bty="o", lwd=1.5, bg= bg_col)
As you can see, I left your rect
call in there, just for comparison. There was a short note in ?addtable2plot
that said:
If bg is a matrix of colors of the same dimensions as x, those colors will be the backgrounds of the cells. The default is no background color.
which is how I figured out how to do this.