Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change plot area background color

Tags:

plot

r

xts

I would like to do a graph in R using our company colors. This means the background of all charts should be a light blue, the plotting region however should be white. I was searching for answers and found that drawing a rect does the job (almost). However the plotting region is now white and the graph not visible anymore. Is this even possible?

getSymbols('SPY', from='1998-01-01', to='2011-07-31', adjust=T)

GRAPH_BLUE<-rgb(43/255, 71/255,153/255)
GRAPH_ORANGE<-rgb(243/255, 112/255, 33/255)
GRAPH_BACKGROUND<-rgb(180/255, 226/255, 244/255)

par(bg=GRAPH_BACKGROUND)

colorPlottingBackground<-function(PlottingBackgroundColor = "white"){
  rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col ="white")
}

plot.xts(SPY, col=GRAPH_BLUE)
colorPlottingBackground()
like image 1000
MichiZH Avatar asked Dec 02 '22 18:12

MichiZH


1 Answers

I know you already accepted @plannapus's answer, but this is a much simpler solution

par(bg="lightblue")
plot(0, 0, type="n", ann=FALSE, axes=FALSE)
u <- par("usr") # The coordinates of the plot area
rect(u[1], u[3], u[2], u[4], col="white", border=NA)

par(new=TRUE)
plot(1:10, cumsum(rnorm(10)))

What you basically do is to overlay two plots using par(new=TRUE): one with only a white rectangle; and another one with the contents you actually want to plot.

enter image description here

like image 135
Backlin Avatar answered Jan 07 '23 12:01

Backlin