rlinepolygonshading

Shading the area under a line with polygon() in R


I am trying to fill the area under a line using polygon(), but the area is filled above instead.

I have been looking around for past similar questions but they either use solutions like predict, or dnorm, which do not seem to fit my case.

This is my code:

# Playfair's chart
library("HistData")
data(Arbuthnot)
data("Wheat")
data("Wheat.monarchs")

with(Wheat, {
  plot(x = Year, y = Wheat, type = "s",
       ylim = c(0, 105), ylab = "Price of the Quarter of Wheat",
       panel.first = grid(col=gray(.9), lty = 1))
  lines(Year, Wages, col = "red", lwd = 2)
})

polygon(c(min(Wheat$Year), Wheat$Year, max(Wheat$Year)),
        c(0, Wheat$Wages, 0),
        col = "gray")

And this is the result.

Probably a noob question but still could not figure out how to do it. I know I could try with ggplot2, but I would like to try with standard graphics first.


Solution

  • Seems like you almost got it. There are missing values in Wages (for the last 3 years). If you remove these before drawing the polygon, your code works.

    with(Wheat[!is.na(Wheat$Wages),],
         polygon(c(min(Year), Year, max(Year)), c(0, Wages, 0),col = "gray"))
    

    enter image description here