[r] Change background color of R plot

All right, let's say I have the following plot.

df = data.frame(date=c(rep(2008:2013, by=1)),
                value=c(303,407,538,696,881,1094))

barplot(df$value, main="TITLE", col="gray", ylab="People", xlab="Years")

How can I change the background to navy blue?

I know this is possible with ggplot2, but not sure if I can do this with base graphics.

This question is related to r plot

The answer is


Like

par(bg = 'blue')
# Now do plot

adjustcolor("blanchedalmond",alpha.f = 0.3)

The above function provides a color code which corresponds to a transparent version of the input color (In this case the input color is "blanchedalmond.").

Input alpha values range on a scale of 0 to 1, 0 being completely transparent and 1 being completely opaque. (In this case, the code for the translucent shad of "blanchedalmond" given an alpha of .3 is "#FFEBCD4D." Be sure to include the hashtag symbol). You can make the new translucent color into the background color by using this function provided by joran earlier in this thread:

rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "blanchedalmond")

By using a translucent color, you can be sure that the graph's data can still be seen underneath after the background color is applied. Hope this helps!


I use abline() with extremely wide vertical lines to fill the plot space:

abline(v = xpoints, col = "grey90", lwd = 80)

You have to create the frame, then the ablines, and then plot the points so they are visible on top. You can even use a second abline() statement to put thin white or black lines over the grey, if desired.

Example:

xpoints = 1:20
y = rnorm(20)
plot(NULL,ylim=c(-3,3),xlim=xpoints)
abline(v=xpoints,col="gray90",lwd=80)
abline(v=xpoints,col="white")
abline(h = 0, lty = 2) 
points(xpoints, y, pch = 16, cex = 1.2, col = "red")

After combining the information in this thread with the R-help ?rect, I came up with this nice graph for circadian rhythm data (24h plot). The script for the background rectangles is this:

root script:

>rect(xleft, ybottom, xright, ytop, col = NA, border = NULL)

My script:

>i <- 24*(0:8)
>rect(8+i, 1, 24+i, 130, col = "lightgrey", border=NA)
>rect(8+i, -10, 24+i, 0.1, col = "black", border=NA)

The idea is to represent days of 24 hours with 8 h light and 16 h dark.

Cheers,

Romário


Old question but I have a much better way of doing this. Rather than using rect() use polygon. This allows you to keep everything in plot without using points. Also you don't have to mess with par at all. If you want to keep things automated make the coordinates of polygon a function of your data.

plot.new()
polygon(c(-min(df[,1])^2,-min(df[,1])^2,max(df[,1])^2,max(df[,1])^2),c(-min(df[,2])^2,max(df[,2])^2,max(df[,2])^2,-min(df[,2])^2), col="grey")
par(new=T)
plot(df)