Ryan Garnett
Ryan Garnett

Reputation: 261

Conditional formatting of plot using ggplot2

I am writing a custom package that leverages ggplot2. The purpose is to make standard plots that follow company branding and style.

Within the functions a user would identify inputs to arguments. Depending on the plot type the scale used would need to be different (i.e. discrete values vs. continuous values). I would like the function to select the appropriate scale based on the data type of the argument.

scatter_plot_multiple <- function(data, xaxis, yaxis, grouping, title = "", subtitle = "", xlabel = "", ylabel = "") {
      xaxis <- enquo(xaxis)
      yaxis <- enquo(yaxis)
      grouping <- enquo(grouping)
      
      ggplot(data) +
        aes(!!xaxis, !!yaxis, colour = !!grouping) +
        geom_point() +
        labs(title = title,
             subtitle = subtitle,
             x = xlabel,
             y = ylabel) +
        customTheme() +
        custom_scale_colour()
}

Within the previous function I would like the custom_scale_colour() to change based on the data type of the grouping argument. For example:

scatter_plot_multiple(mpg, cty, hwy, drv) would use custom_scale_colour()

scatter_plot_multiple(mpg, cty, hwy, cyl) would use custom_gradient_colour()

I am unsure how to tackle this challenge.

Upvotes: 1

Views: 580

Answers (1)

rjen
rjen

Reputation: 1982

In ggplot2, you can add a conditional statement like you can in a magrittr/dplyr pipe. One inserts an if statement wrapped in curly brackets: + {if ([condition]) {[action]}}. Applied to quoted variable names inside a function, using this approach could look like the following.

library(ggplot2)
library(dplyr)
library(rlang)

scatter_plot_multiple <- function(data, xaxis, yaxis, grouping, title = "", subtitle = "", xlabel = "", ylabel = "") {

  xaxis <- enquo(xaxis)
  yaxis <- enquo(yaxis)
  grouping <- enquo(grouping)
  groupingClass <- class(pull(data, as_name(grouping)))

  ggplot(data) +
    aes(!!xaxis, !!yaxis, colour = !!grouping) +
    geom_point() +
    labs(title = title,
         subtitle = subtitle,
         x = xlabel,
         y = ylabel) +
    customTheme() +
     {if (groupingClass == 'character') {
       custom_scale_colour()}} +
     {if (groupingClass == 'numeric') {
       custom_gradient_colour()}}
}

Upvotes: 2

Related Questions