Hands-on Exercise 9A: Creating Ternary Plot with R

Author

Kristine Joy Paas

Published

June 13, 2024

Modified

June 13, 2024

1 Overview

This hands-on exercise covers Chapter 13: Creating Ternary Plot with R.

In this exercise, I learned:

  • How to create ternary plots

2 Getting Started

2.1 Loading the required packages

For this exercise we will use the following R packages:

  • ggtern: ggplot2 extension to plot ternary graphs

  • tidyverse: data analytics tools for r

  • plotly: for mapping interactive graphs

pacman::p_load(plotly, ggtern, tidyverse)

2.2 Importing data

We will use the Singapore Residents by Planning AreaSubzone, Age Group, Sex and Type of Dwelling, June 2000-2018. It is called respopagsex2000to2018_tidy.csv and is in csv file format.

pop_data <- read_csv("data/respopagsex2000to2018_tidy.csv") 

3 Data Preparation

Next, use the mutate() function of dplyr package to derive three new measures, namely: young, active, and old.

agpop_mutated <- pop_data %>%
  mutate(`Year` = as.character(Year))%>%
  spread(AG, Population) %>%
  mutate(YOUNG = rowSums(.[4:8]))%>%
  mutate(ACTIVE = rowSums(.[9:16]))  %>%
  mutate(OLD = rowSums(.[17:21])) %>%
  mutate(TOTAL = rowSums(.[22:24])) %>%
  filter(Year == 2018)%>%
  filter(TOTAL > 0)

4 Plotting Ternary Diagram with R

4.1 Plotting a Static Ternary Graph

ggtern(data=agpop_mutated,aes(x=YOUNG,y=ACTIVE, z=OLD)) +
  geom_point()

This plots the points with respect to 3 dimensions.

We can also add some colors and formatting.

ggtern(data=agpop_mutated, aes(x=YOUNG,y=ACTIVE, z=OLD)) +
  geom_point() +
  labs(title="Population structure, 2015") +
  theme_rgbw()

4.2 Plotting an Interactive Ternary Graph

We can use plotly to plot an interactive ternary graph.

label <- function(txt) {
  list(
    text = txt, 
    x = 0.1, y = 1,
    ax = 0, ay = 0,
    xref = "paper", yref = "paper", 
    align = "center",
    font = list(family = "serif", size = 15, color = "white"),
    bgcolor = "#b3b3b3", bordercolor = "black", borderwidth = 2
  )
}

# reusable function for axis formatting
axis <- function(txt) {
  list(
    title = txt, tickformat = ".0%", tickfont = list(size = 10)
  )
}

ternaryAxes <- list(
  aaxis = axis("Young"), 
  baxis = axis("Active"), 
  caxis = axis("Old")
)

# Initiating a plotly visualization 
plot_ly(
  agpop_mutated, 
  a = ~YOUNG, 
  b = ~ACTIVE, 
  c = ~OLD, 
  color = I("black"), 
  type = "scatterternary"
) %>%
  layout(
    annotations = label("Ternary Markers"), 
    ternary = ternaryAxes
  )
0%20%40%60%80%100%100%80%60%40%20%0%100%80%60%40%20%0%
YoungActiveOldTernary MarkersTernary MarkersTernary Markers

5 Reflections

I thought the only way to visualize 3 dimensions is via x, y, z axis and cubes. It is enlightening to see that there are alternative ways to visualize it.