R - s3 plot theme

Viewed 58

I want to have one exported function my_theme() that can be applied to different chart types (ggplot, highcharter, plotly). I tried using S3 methods but there are a few problems:

  • I can only figure out how to use the pipe |> vs the + operator for ggplot objects
  • I can't seem to use this in ggplot2::theme_set(), I might create a separate use_my_theme() function to do this

Any advice would be appreciated:

library(highcharter)
library(ggplot2)

# functions
my_theme <- function(p, ...) {
  UseMethod("my_theme", p)
}

my_theme.gg <- function(p, ...) {
  p + 
    theme_dark(...)
}

my_theme.highchart <- function(p, ...) {
  p |> 
    hc_add_theme(hc_theme_darkunica(...))
}


# highcharter
highcharter::highcharts_demo() |> 
  my_theme()

# ggplot
ggplot2::qplot(mpg, wt, data = mtcars) |> 
  my_theme()                        # ^^^ how to make '+' instead?

theme_set(my_theme())   # doesn't work (and future plots will fail)
theme_set(theme_gray()) # revert back
1 Answers

I didn't figure it out on my own but adding a missing() condition does the trick. This wouldn't work if there is ggplot2 and another plotting library that is built with operators + instead of pipes |>.

library(highcharter)
library(ggplot2)

# methods
my_theme <- function(p, ...) {
  if (missing(p)) {
    return(theme_dark(...))
  }
  
  UseMethod("my_theme", p)
}


my_theme.gg <- function(p, ...) {
  p + theme_dark(...)
}


my_theme.highchart <- function(p, ...) {
  p |> hc_add_theme(hc_theme_darkunica(...))
}


# highcharter
highcharts_demo() |> my_theme()

# ggplot
gg <- quickplot(group, weight, data = PlantGrowth, color = group) 

gg |> my_theme()

theme_set(my_theme())
gg

theme_set(theme_gray())
gg
Related