Search code examples
rr-plotly

Making a predefined layout for plotly in R


I would like to make a predefined layout that I can use for my plot functions that I have created so as not to repeat myself everytime I make a plot. For example, I tried to do sth like the following which doesn't work and gives an error:

custom_layout <- function(){
  plotly::layout(
    xaxis = list(title = ""),
    yaxis = list(title = ""),
    title = list(text = title, y = 0.98)
  )
}

plot_bar <- function(title, dt, x, y, fill){
  plot_ly(dt, x =  ~x, y =  ~y, type = "bar",
          color =  ~ fill, split =  ~ fill) %>% 
    custom_layout()}

plot_line <- function(title, dt, x, y, fill){
  plot_ly(dt, x = ~x, y = ~y, type="scatter",
          split = ~fill, mode="lines+markers") %>% 
    custom_layout()}

I call these 2 plotting functions multiple times in my code. I have also other predefined plotting functions like plot_line and plot_bar and I use the same layout for them as well but now manually adding the layout like in the following:

plot_bar <- function(title, dt, x, y, fill){
  plot_ly(dt, x =  ~x, y =  ~y, type = "bar",
          color =  ~ fill, split =  ~ fill) %>% 
  layout(
    xaxis = list(title = ""),
    yaxis = list(title = ""),
    title = list(text = title, y = 0.98)

Ideally, I would like to define it like in the first scenario with a predefined layout that I could use later for every plotting function which is not working for me. Is there a way to do it with native plotly and not ggplot2?


Solution

  • You need to make the custom_layout() function take p as its first argument (just like layout() does).

    library(tibble)
    dt <- tibble(x=1:4, y=3:6, fill=1:4)
    
    custom_layout <- function(p, title){
      plotly::layout(p,
                     xaxis = list(title = ""),
                     yaxis = list(title = ""),
                     title = list(text = title, y = 0.98)
      )
    }
    
    plot_bar <- function(title, dt, x, y, fill){
      plot_ly(dt, x =  ~x, y =  ~y, type = "bar",
              color =  ~ fill, split =  ~ fill) %>% 
        custom_layout(title=title)}
    
    
    plot_bar(title="myplot", dt, "x", "y", "fill")
    

    enter image description here