Plotting add_trace from within a function: Plotly

982 views Asked by At

I am trying to "functionize" my plot statements. If i want to add an additional trace from another dataframe, i am getting an error that the values on the y axis do not equal the first number of values in the first dataframe. I am not certain why this is relevant.

library(tidyverse)
library(plotly) 
library(lubridate)

Date <- seq(as.Date("2016-10-1"), as.Date("2018-09-01"), by="month")
Values <- c(2,3,4,3,4,5,6,4,5,6,7,8,9,10,8,9,10,11,12,13,11,12,13,14)

Date2 <- seq(as.Date("2018-07-1"), as.Date("2018-09-01"), by="month")
Values2 <- c(16,17,18)

df <- tibble::tibble(Date, Values)
df2 <- tibble::tibble(Date2, Values2)



testfunction <- function(x, y, y2){

p <-  plot_ly(df,x = ~x, y = ~y, colors = "Blues", type = 'scatter', mode = 'lines') %>% 
     add_trace(data = df2, y = ~y2, line = list(color = 'rgb(255, 36,1)', width = 2.25)) %>% 
     layout(xaxis = list(tickformat = "%b %e"))

      p  
}

testfunction(Date, Values, Values2)

#Error: Column `y` must be length 1 or 24, not 3
1

There are 1 answers

2
Weihuang Wong On BEST ANSWER

Notice that Date, Values, and Values2 are objects that exist in your global environment. So, testfunction is actually using those objects in the call to plot_ly. To demonstrate this, try removing df in the plot_ly call -- you should still be able to get a plot (i.e. plot_ly isn't actually using the values in the dataframe). However, I suspect what you're trying to do is to specify variable names in your dataframe in the arguments to your function. In which case, try

testfunction <- function(x, y, x2, y2) {
  x <- enquo(x)
  y <- enquo(y)
  x2 <- enquo(x2)
  y2 <- enquo(y2)
  plot_ly(df, x = x, y = y, type = "scatter", mode = "lines") %>%
    add_trace(x = x2, y = y2, data = df2)
}

testfunction(Date, Values, Date2, Values2)

with a hat tip to this question and answer: Pass variables as parameters to plot_ly function