Sharl
Sharl

Reputation: 175

Shading area of curve from x axis in R

So I have a graph that goes below and above the x axis and am wanting to shade the area between the line and 0

enter image description here

Here I've tried to use the polygon function but it gives me the area under the curve only.

plot(year,difference1,type="l")
polygon(year,difference1,col='120',panel.first=abline(h=1,lty=3))

Upvotes: 0

Views: 846

Answers (1)

Chris Holbrook
Chris Holbrook

Reputation: 2636

Since polygon connects first and last point to complete the boundary, just add a point to beginning and end of your line that forces through y=0.

With some arbitrary values for year and difference1:

year=1:10
difference1=c(1,2,5,4,-1,-5,2,5,3,-1)
plot(year,difference1,type="l")
polygon(c(year[1],year,year[length(year)]),c(0,difference1,0),col='120',
    panel.first=abline(h=1,lty=3))

enter image description here

Upvotes: 3

Related Questions