【问题标题】:Plotting add_trace from within a function: Plotly从函数中绘制 add_trace:Plotly
【发布时间】:2019-02-26 15:56:47
【问题描述】:

我正在尝试“功能化”我的情节陈述。如果我想从另一个数据帧添加额外的跟踪,我会收到一个错误,即 y 轴上的值不等于第一个数据帧中的第一个值。我不确定为什么这是相关的。

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

【问题讨论】:

    标签: r dataframe plotly lubridate ggvis


    【解决方案1】:

    请注意,Date、Values 和 Values2 是您的全局环境中存在的对象。所以,testfunction 实际上是在对plot_ly 的调用中使用这些对象。为了证明这一点,请尝试在 plot_ly 调用中删除 df - 您仍然应该能够获得绘图(即 plot_ly 实际上并未使用数据框中的值)。但是,我怀疑您正在尝试做的是在您的函数参数中的数据框中指定变量名称。在这种情况下,请尝试

    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)
    

    这个问题和答案的帽子提示:Pass variables as parameters to plot_ly function

    【讨论】:

    • @Weihuang:非常感谢您抽出宝贵的时间和帮助回答这个问题。看起来显式调用 df2 x 轴可以使绘图工作。如果我将 enquo() 函数添加到上面的图中,则 x 和 y 变量之前的 ~ 会导致空白图。因此,必须删除它们,就像您在示例中所做的那样。你知道这是为什么吗?非常感谢。
    • 很难在评论中找到答案。我建议将您的问题作为新的 SO 问题发布。这可能是普遍的兴趣。
    猜你喜欢
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 2016-07-31
    相关资源
    最近更新 更多