Hands-on_Ex09(a)

Published

June 14, 2024

Creating Ternary Plot with R

Overview

Data Preparation

Install and launching R package

pacman::p_load(plotly, ggtern, tidyverse)

Import Data

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

Prepate the Data

agpop_mutated <- pop_data %>%
  mutate('YEAR' = as.character(Year)) %>%
  spread(AG, Population) %>%
  mutate(across(4:22, as.numeric)) %>%
  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)

Plotting Ternary

Plotting a static ternary diagram

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

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

Plotting an interative ternary diagram

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
  )
}
axis <- function(txt){
  list(
    title = txt, tickformat = ".0%", tickfont = list(size = 10)
  )
}
ternaryAxes <- list(
  aaxis = axis("Young"),
  baxis = axis("Active"),
  caxis = axis("Old")
)
plot_ly(
  agpop_mutated,
  a = ~YOUNG,
  b = ~ACTIVE,
  c = ~OLD,
  color = I("black"),
  type = "scatterternary"
) %>%
  layout(
    annotations = label("Ternary Markers"),
    ternary = ternaryAxes
  )