How to make an age pyramid plot in R

in visualization •  7 years ago  (edited)

There are many cases in which visualizing the data in a certain way helps in making different considerations. For example, you have a population of individuals and you want to divide them per age groups of ten years 21-30 years old, 31-40 years old and so on and so forth.

There are also males and females in your population so you have to keep separate the two categories. The plot we make with R is called age pyramid plot and is used to visualize how the number of individuals is distributed per each age group

The R code in the snippet below explains this in just a few lines where each step is well commented. However, the steps are

a) loading the data and

b) visualizing it

In this example, you can even copy paste the code in Rstudio as there are no particular libraries to import. However, try to understand the code (by going through the lines and comments) before you run it

// the following code creates the groups
groups = c("20-30", "31-40", "41-50", "51-60", "61-70")
// there are 8 males in the first group, 28 in the second and so on
males = c(8,28.27,24,10)
females = c(10,30.25,24,15)

// create the plot with the right parameters
par(mar=c(0.5, 5, 0.5, 1))
plot.new()
plot.window(xlim=c(-50, 50), ylim=c(-1.5, 5.5))
ticks = seq(-50, 50, 5)
y = 1:5
h = 0.2
// set the axes
lines(rep(0, 2), c(-1.5, 5.5), col="grey")
segments(-50, y, 50, y, lty="dotted")
rect(-males, y-h, 0, y+h, col="dark grey")
rect(0, y-h, females, y+h, col="light grey")
mtext(groups, at=y, adj=1, side=2, las=2)
par(cex.axis=0.5, mex=0.5)
axis(1, at=ticks, labels=abs(ticks), pos=0)

//add the legend at the end
tw = 1.5*strwidth("females")
rect(-tw, -1-h, 0, -1+h, col="dark grey")
rect(0, -1-h, tw, -1+h, col="light grey")
text(0, -1, "males", pos=2)
text(0, -1, "females", pos=4)

And this is how the result looks

Enjoy :-)

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

The @OriginalWorks bot has determined this post by @datatreemap to be original material and upvoted it!

ezgif.com-resize.gif

To call @OriginalWorks, simply reply to any post with @originalworks or !originalworks in your message!

To enter this post into the daily RESTEEM contest, upvote this comment! The user with the most upvotes on their @OriginalWorks comment will win!

For more information, Click Here! || Click here to participate in the @OriginalWorks sponsored writing contest(125 SBD in prizes)!
Special thanks to @reggaemuffin for being a supporter! Vote him as a witness to help make Steemit a better place!