Area Plots in Base Plotting System

V.Rajaraman

Area plots are easy to make with ggplot2. The same effect can be achieved in base plotting system too, and this gives you finer control over the plot.

Here we simulate the daily guest check in and check out numbers of a small country side hotel.

# generate simulated guest traffic
n = 100
x = 1:n
set.seed(1)
y1 = rnorm(n, 10, 3) + 3
set.seed(2)
y2 = rnorm(n, 5, 3) + 1

The bottom plot represents guests checking out, so it is inverted and plotted below the y=0 line. Since these are randomly generated numbers, you need to make some level shifing to avoid the red and green colors running into each other !

# adjust the orientation and location
y1 = y1 + abs(min(y1))
y2 = y2 + abs(min(y2))
y2 = -y2
y3 = y1 + y2
# the y axis range; give some space for the legend
mx = max(y1)
mn = min(y2) - 1.5

The polygon() command is handy for this. You need to provide a closed path of points to get a filled polygon, so we add a couple of zeros at the end of the data points to close the loop.

The final result looks like this:

# prepare the plot limits
plot(x, y1, ylim = c(mn, mx), xlab = "Day", ylab = "Guests", main = "Daily Guest Register", 
    type = "n")
# close the polygons by looping back to the starting point
polygon(c(x, n, 1), c(y1, 0, 0), border = NA, col = "yellowgreen")
polygon(c(x, n, 1), c(y2, 0, 0), border = NA, col = "orangered")
# the net guest count on a given day
lines(x, y3)
points(x, y3, pch = 16)
# high water mark representing the total capacity of the hotel
abline(h = mx + 1, lty = 2, col = "gray")
legend("bottom", horiz = TRUE, bty = "n", pt.cex = c(3, 3, 1), col = c("yellowgreen", 
    "orangered", 1), pch = 19, lwd = c(NA, NA, 1), legend = c("Check in", "Check out", 
    "Occupancy"))

plot of chunk unnamed-chunk-3