Advertisement
Guest User

Untitled

a guest
Mar 3rd, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1.  
  2. # Author: tim
  3. ###############################################################################
  4.  
  5. library(HMDHFDplus) # install from CRAN
  6.  
  7. # set 'us' and 'pw' as strings in the console equal to
  8. # your HMD username and password
  9. Pop <- readHMDweb("SWE", "Population", username = us, password = pw)
  10.  
  11. library(RColorBrewer)
  12.  
  13. range(Pop$Year)
  14. ramp <- colorRampPalette(brewer.pal(9,"YlGnBu"),space="Lab")
  15.  
  16. # single years
  17. years.all <- unique(Pop$Year)
  18. # years ending in 0 since 1870
  19. years <- years.all[years.all %% 10 == 0 & years.all >= 1870]
  20.  
  21. # color by mean age:
  22. meana <- c()
  23. for (i in 1:length(years)){
  24. x <- Pop$Male1[Pop$Year == years[i]]
  25. meana[i] <- sum(x*.5:110.5) / sum(x)
  26. }
  27. ints <- unique(floor(meana))
  28.  
  29. cols <- ramp(length(ints)+6)
  30.  
  31.  
  32. pdf("/home/tim/workspace/Other/PAAdatavizgraphic.pdf",height=3,width=9)
  33. par(mai=c(.1,0,0,.1), xaxs="i",yaxs="i",xpd=TRUE)
  34. plot(NULL,xlim=c(-.028,.155),ylim=c(0,110),axes=FALSE,xlab="",ylab="")
  35. x.at <- 0
  36. for (i in 1:length(years)){
  37. x <- Pop$Male1[Pop$Year == years[i]]
  38.  
  39. # this ugly bit is to cut off the top outline of the pyramid if
  40. # the highest ages have 0 pop. Ugly but swift to implement. Not
  41. # worth trying to understand what's happening in this little chunk
  42. max.x <- 111 - max(cumsum(diff(cumsum(cumsum(rev(x))==0))))
  43. x <- x[1:max.x]
  44.  
  45. # scale to proportion!
  46. x <- x / sum(x)
  47. color <- cols[which(ints == floor(meana[i]))+2]
  48.  
  49. # the pyramid slice (just males here)
  50. polygon(c(0, rep(-x, each = 2),0) + x.at, rep(0:max.x, each = 2), col = color,
  51. border = "white", lwd = .5)
  52. x.at <- x.at + .01 # shift right
  53. }
  54. # legend
  55. rect(x.at - .007, seq(0, 100, by = 10) * .7 + .1, x.at, seq(10, 110, by = 10) * .7 + .1, col = colors, border = "white")
  56. text(x.at, seq(0, 100, by = 10) * .7 + .1, ints, pos = 4, cex = .8)
  57. text(x.at - .003, 110 * .7 + .1, bquote(bar(x)), pos = 3)
  58.  
  59. dev.off()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement