I’m not (currently) a big R user, but learnt some basics in a statistics course I took recently.

I’m passionate about open source, so R appealed to me from the outset. Having done bits of numerical programming I was also impressed by how easy it made it to manipulate numerical data.

In a subsequent course on ecology, they suggested we use matlab to plot some data, which would have been fine until I found out that I either had to buy a copy of matlab to use it on my laptop, or use one of the managed windows machines on the university network (and I generally do everything I can to avoid ever having to use windows).

I therefore tried to use R to mimic what matlab was doing, but was stumped on how to get R to replicate the matlab plot, which had grey margins, but a white plot area. I couldn’t find an exact solution online, but after a bit of googling and playing about I came up with the solution below.

Firstly the entire background is set to the margin colour. Then the panel.first argument (type ?panel.default at the R prompt to get more info on this) is used to draw a white rectangle over the plot area before the lines are drawn. The par(“usr”) paramater is used to determine the coordinates of the plotting area.

# R script to plot ln(x)+1 on a white background with grey margins
# Create a function that we wish to plot
eq = function(x){log(x)+1};
# Create vectors with x and y values
x = (1:100);
y = eq(x)
# Set background colour for whole plot
par(bg = 'gray')
# Plot x against y using a line (type) and create a white rectangle for the plot area using panel.first
plot(x,y,type="l",panel.first=rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "white"))
# Add a title
title("A plot of y=ln(x)+1 on a white background with grey margins")

If you’re just interested in plotting a function, then it’s even easier to do the above with the “curve” function as shown below, as this also accepts the panel.first argument.

# R Script to plot ln(x)+1 using curve with grey margins
# Set background colour for whole plot
par(bg = 'gray')
# Use curve to plot the function
curve(log(x)+1,from=0, to=100, n=200, panel.first=rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "white"))
# Add a title
title("A plot of y=ln(x)+1 on a white background with grey margins")

### Like this:

Like Loading...

Thanks for posting! I am also looking to never use Matlab again (but I don’t want anyone to know).