knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
The demViz
package provides simple ggplot2
wrapper functions for common graphs used in demography, public health and the social sciences.
One of the most common plots made when comparing estimates or data for different groupings (by location, sex, age, race, income etc.) is a line graph.
library(demViz) library(ggplot2) library(data.table) # create population projections thailand_population_estimates <- demCore::ccmpp( inputs = demCore::thailand_initial_estimates, settings = list( years = seq(1960, 1995, 5), sexes = c("female", "male"), ages = seq(0, 80, 5), ages_survival = seq(0, 85, 5), ages_asfr = seq(15, 45, 5) ) ) thailand_population_estimates[, source_name := "CCMPP Projection"] thailand_population_estimates[, source_type := "Estimate"] thailand_population_data <- copy(demCore::thailand_data$population) thailand_population_data[, source_name := "Census Data"] thailand_population_data[, source_type := "Data"] # combine projections with population data thailand_population <- rbind( thailand_population_estimates, thailand_population_data, use.names = T ) # add 'age_name' column hierarchyUtils::gen_name(thailand_population, col_stem = "age") thailand_population[, age_name := factor(age_name, levels = unique(thailand_population[, age_name]))] # add column differentiating the data to be plotted as a point thailand_population[, point := source_type == "Data"]
To demonstrate demViz::plot_line_graph
we'll use population projections and population data from the demCore
package. This is what the plot input data looks like after some basic prep.
thailand_population
plot_line_graph
requires that we specify what column in the input data corresponds to the x-value (x_col
) and the y-value (y_col
). The point_col
argument specifies the data we want to plot as points rather than a line.
The scale_manual
argument is a flexible argument that allows the user to specify manual values for different aesthetics like colour or linetype etc. Each aesthetic must have col
, legend_title
and scale
attributes.
plot_line_graph( dt = thailand_population, plot_title = "Thailand Population Time Series", x_col = "year", x_axis_title = "Year", y_col = "value", y_axis_title = "Population", y_axis_commas = TRUE, point_col = "point", scale_manual = list( colour = list( col = "source_name", legend_title = "Source", scale = c("Census Data" = "#A55B3B", "CCMPP Projection" = "#4DAF4A") ) ) )
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.