# Shaded graphs in R

Sometimes it is comprehensive to visualize complex distribution of a model with shaded graph using the percentiles as boundaries. Following are two graphs – dirty and neat examples of the Von Bertalanffy Growth Model, showing growth of fish with increasing age.

Shaded graphs are easier to plot, but difficult to understand the trick. Essentially, this can be achieved using the *polygon ()* function in R.

**Computing the percentiles from data**

If suppose we have data from 50 fish, 10 each from Age 1 to Age 5:

mydata Age1 Age2 Age3 Age4 Age5 [1,] 35.63813 59.81503 97.39460 102.23921 134.7052 [2,] 32.10304 68.34917 86.97411 94.06250 118.3878 [3,] 35.93959 61.62869 88.71316 113.95664 127.2596 [4,] 30.73885 56.36995 95.56985 105.57710 129.5275 [5,] 29.88816 59.83590 79.20284 113.07792 120.7841 [6,] 31.16976 48.10858 84.04000 80.52727 136.6355 [7,] 30.71656 47.70394 82.34205 87.58575 123.5584 [8,] 31.05663 63.18036 101.23041 108.09523 153.9219 [9,] 34.99453 57.75032 96.64804 102.09258 122.3556 [10,] 32.40417 57.13938 86.48527 95.42354 121.9671

Following is a code to generate a similar data as above in R:

The quantile () function in R can be used to compute the percentiles. To find out the percentiles column wise (for each age), use the sapply() function :

mynewdata<-sapply(as.data.frame(mydata),FUN=quantile) mynewdata Age1 Age2 Age3 Age4 Age5 0% 29.88816 47.70394 79.20284 80.52727 118.3878 25% 30.81829 56.56231 84.65132 94.40276 122.0642 50% 31.63640 58.78268 87.84363 102.16590 125.4090 75% 34.34694 61.18049 96.37849 107.46570 133.4108 100% 35.93959 68.34917 101.23041 113.95664 153.9219

**Shading between percentile boundaries**

A polygon is drawn between the boundaries and a colour is specified for shading the region. This will need the XY co-ordinates in the right order (clockwise or anti-clockwise). Here the X-axis is the age of fish and Y-axis are the percentile boundaries.

To draw a polygon to shade the region between 25% and 75% boundaries, we have to extract Y values from the data.

mynewdata25<-mynewdata[2,] > mynewdata25 Age1 Age2 Age3 Age4 Age5 32.10304 68.34917 86.97411 94.06250 118.38777 mynewdata50<-mynewdata[3,] > mynewdata50 Age1 Age2 Age3 Age4 Age5 35.93959 61.62869 88.71316 113.95664 127.25961 mynewdata75<-mynewdata[4,] > mynewdata75 Age1 Age2 Age3 Age4 Age5 30.73885 56.36995 95.56985 105.57710 129.52751

Now we can first plot the graph using the 50% data i.e., mydata50

Now add the shades between boundary percentiles into the graph using the polygon ()

polygon(X co-ordinates, Y co-ordinates, colour, border)

The polygon will mask the initial plot showing the 50% line. This can be re-plotted by adding the following command.

lines(mynewdata50,lty=1,lwd=2)

title("Fish Growth")

Posted on March 5, 2013, in Uncategorized. Bookmark the permalink. Leave a comment.

## Leave a comment

## Comments 0