Search code examples
rplotgraph

R: How to align lines with polygon


I'm unable to get the polygon to align with the curve. I'll put the code here:

critvalmax <- qt(0.975,df=4)
critvalmin <- qt(0.025,df=4)
xvals <- seq(-5, 5, length=100) 
fx.samp.t <- dt(xvals, df=4)

plot(xvals, dnorm(xvals), col="white") 
lines(xvals, fx.samp.t, lty=1, lwd=2)
abline(v= critvalmin, lty=2)
abline(v= critvalmax, lty=2)
abline(h=0, lty=3)
polygon(cbind(c(critvalmin, xvals[xvals>=critvalmin & xvals<=critvalmax], critvalmax, critvalmax), c(0, dt(critvalmin, df=4), fx.samp.t[xvals>=critvalmin & xvals<=critvalmax], 0)), density=10, lty=3)

The problematic plot The result is that the polygon is drawn a bit to the right and I can't find a solution by myself. Also, the left bottom corner doesn't seem to fill properly.


Solution

  • I removed some variables in your polygon like the second critvalmax and dt(critvalmin, df=4) and cbind. The dt(critvalmin, df=4) seems to have slightly moved your polygon by 0.02558082 to right. You can use the following code:

    critvalmax <- qt(0.975,df=4)
    critvalmin <- qt(0.025,df=4)
    xvals <- seq(-5, 5, length=100) 
    fx.samp.t <- dt(xvals, df=4)
    
    plot(xvals, dnorm(xvals), col="white") 
    lines(xvals, fx.samp.t, lty=1, lwd=2)
    abline(v= critvalmin, lty=2)
    abline(v= critvalmax, lty=2)
    abline(h=0, lty=3)
    polygon(c(critvalmin, xvals[xvals>=critvalmin & xvals<=critvalmax], critvalmax), c(0, fx.samp.t[xvals>=critvalmin & xvals<=critvalmax], 0), density=10, lty=3)
    

    Created on 2022-08-31 with reprex v2.0.2

    polygon only needs your x and y:

    vectors containing the coordinates of the vertices of the polygon.

    And the density:

    the density of shading lines, in lines per inch. The default value of NULL means that no shading lines are drawn. A zero value of density means no shading nor filling whereas negative values and NA suppress shading (and so allow color filling).