0

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 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

@ Weihuang: Thanks so much for your time and help with this answer. It looks like explicitly calling the df2 x axis gets the plot to work. If i add the enquo() functions to my plots above, the ~ before the x and y variable results in a blank plot. So they must be removed, as you did in your example. Do you know why this is? Thank you very much.
It's hard to fit the answer in a comment. I would recommend posting your question as a new SO question. It might be of general interest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.