Search code examples
rgooglevis

How to graph population age structure by sex using GoogleVis and R?


Am trying to create a graph of population structure by age and sex using R and googleVis. However the graph never fully loads on the browser I just get a "loading" message and no output. The command am using in RStudio is

plot(gvisMotionChart(data, idvar = "id", timevar = "ExpYear", xvar = "ExpYear", yvar = "n", colorvar = "AgeGroup",sizevar = "n"))

My data My data basically shows the number of people in a particular age bracket (AgeGroup column) in a particular year (between 2000-2014) for a particular gender and can be found here: https://github.com/kilimba/data.

Am not sure how to go about debugging, or whether it is even a problem with the code or data. Am also new to bot R and GoogleVis so any help would be greatly appreciated.

Tumaini


Solution

  • You are using the same variable for timevar and xvar dimension.

    Try for example (time = year, x = AgeGroup, y = n and color = sex):

    plot(gvisMotionChart(data, idvar = "id", timevar = "ExpYear", xvar = "AgeGroup", yvar = "n", colorvar = "Sex"))
    

    To see the motion you have to restructure your data so that you have one ID for all years. Set ID for example as combination of AgeGroup and Sex:

    library(dplyr)
    library(tidyr)
    
    df2 <- data %>%
      group_by(ExpYear, AgeGroup, Sex ) %>%
      summarize(n = sum(n)) %>%
      mutate(id = paste(AgeGroup, Sex))
    

    And plot with:

    plot(gvisMotionChart(df2, idvar = "id", timevar = "ExpYear", xvar = "AgeGroup", yvar = "n", colorvar = "Sex"))