A back-to-back barplot from scratch
This example is shown in Figure 3.30 in Paul Murrell's
R Graphics book. Also, be aware of the
Hmisc
package's
histbackback()
function, which creates back-to-back histograms.
The example is built on the
chickwts
built-in data set, which can be accessed using the
data()
function.
library(Hmisc)
data(chickwts)
contents(chickwts)
describe(chickwts)
Our barplots will distinguish the number of chicks above the median weight, so we need to calculate this first. We can view the results using a simple table of frequencies.
chickwts <- upData(chickwts,
median.weight = ifelse(weight > median(weight, na.rm = TRUE), 1, 0),
levels = list(median.weight = c("Below", "Above")))
with(chickwts, table(feed, median.weight))
Now let's turn the table output into a back-to-back barplot. Let's first define the data we'll need to use (i.e.,
datta
), and some parameters we'll need for the plot.
Be aware, the final parameters were found through some trial and error.
# Define the data:
datta <- with(chickwts, table(feed, median.weight))
# Define some parameters:
xlimit <- 15 # dependent on max frequency given in table
ticks <- seq(-xlimit, xlimit, 5) # where to plac the tickmarks
nlines <- nlevels(chickwts$feed) # number of groups
yvals <- 1:nlines # y values for the groups
h <- 0.25 # height of bars
Now let's generate the plot.
par(mar=c(0.5, 5, 0.5, 1))
plot.new() # start a new plot frame
plot.window(xlim=c(-xlimit, xlimit), ylim=c(-2.0, nlines+0.5))
lines(rep(0, 2), c(-2.0, nlines+0.5), col="grey")
segments(-xlimit, yvals, xlimit, yvals, lty="dotted")
rect(-datta[, "Below"], yvals-h, 0, yvals+h, col="dark grey")
rect(0, yvals-h, datta[, "Above"], yvals+h, col="light grey")
mtext(levels(chickwts$feed), at=yvals, adj=1, side=2, las=2)
par(cex.axis=0.5, mex=0.5)
axis(1, at=ticks, labels=abs(ticks), pos = 0)
tw <- 1.5*strwidth("Below")
rect(-tw, -1-h, 0, -1+h, col="dark grey")
rect(0, -1-h, tw, -1+h, col="light grey")
text(0, -1, "Below", pos=2)
text(0, -1, "Above", pos=4)
text(0, -1.5, "Back-to-back Barplot of Chick Weights Below/Above Median Value",
adj = 0.5)