Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading