bgnj2015 bgnj2015 - 1 month ago 7
R Question

Different color inside chart area from background using barplot in R

I am creating a stacked plot using "barplot" in R. I want to set the chart area color to gray and the background to light blue. I can set the background color to light blue but cannot control the color inside the chart area. There are similar questions asked for chartjs but nothing for barplot.Below is the script I was attempting. Is there a way I can have a different color (gray) within the chart area bound by the axes and different color (light blue) outside the axes?

cols <-c("#4F81BD","#8064A2","#9BBB59","#C0504D","#000077")
pdf(file="Figure-check.pdf", width=11.5, height=8)
par(mar=c(10,3,6,7) +.01, bg = "#99CCFF")
barplot(Variabletoplot, main="Figure Title", col= cols, border = TRUE, axes = TRUE, ylab = "YLABEL", bg = "gray")
legend("right", rownames(merge1), fill=cols, horiz=FALSE, title="LEGEND TITLE", xpd=TRUE, inset =c(-.145,0))
dev.off()

Answer

The closest previous answer I could find is How to change the background colour of a subplot/inset in R?.

But the trick is to draw you chart, mainly to get the axis correct, then draw a rectangle, then redraw the barchart over the rectangle (only modified code is shown below):

# Draw barchart to get a plot with correct axes; draw as little as
# possible
barplot(c(foo=1, bar=2.2), names.arg="", col= cols, border = NA, 
  axes = FALSE, ylab = "")

# Draw the background by drawing a rectangle:
rect(par("usr")[1], par("usr")[3], par("usr")[2], 
  par("usr")[4],col = "gray")

# Redraw the barchart with all labels etc. 
barplot(c(foo=1, bar=2.2), main="Figure Title", col= cols, 
  border = TRUE, axes = TRUE, ylab = "YLABEL",
  add=TRUE)
Comments