Search code examples
rggplot2aesthetics

Passing variables to ggplot aes()


I am using ggplot to map the relationship between two attributes of a vector data. The attributes are named by year: v_2000, v_2001, v_2002,... and p_2000, p_2001, p_2002,...The code below works fine

ggplot() +
  geom_spatvector(data=vec, aes(fill = 100*v_2000/p_2000 ),color="black")+
  labs(title="Title", fill="")

But I would like to change it so that I can use a variable year to select the attributes. I have tried the code below but got an error message

yr = 2000
var = paste0("100*v_",yr,"/p_",yr)
ggplot() +
  geom_spatvector(data=vec, aes(fill = !!rlang::sym(var)),color="black")+
  labs(title="Title", fill="")
Error in `ggplot2::geom_sf()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `FUN()`:
! object '100*v_2000/p_2000' not found

Any recommendations?


Solution

  • Here is a solution that first calculates the attribute that is going to be used as fill values. Notice that !!sym is used to set all the names of the variables used, while := is used to create a new column using the variable yr.

    library(ggplot2)
    library(terra)
    library(tidyterra)
    library(dplyr)
    library(rlang)
    
    # Dummy data
    vec <- vect(system.file("ex/lux.shp", package="terra"))
    names(vec)[5:6] <- c("v_2000", "p_2000")
    yr <- 2000
    vec <- vec |>
      # Add new column to the original dataset using variable name and attributes
      mutate(!!sym(paste0("new_",yr)) := 100 * !!sym(paste0("v_",yr)) / !!sym(paste0("p_",yr)) )
    
    # Make ggplot
    ggplot() +
      geom_spatvector(data=vec, aes(fill = !!sym(paste0("new_",yr))),color="black")+
      labs(title="Title", fill="")