簡體   English   中英

從函數內部繪制add_trace:

[英]Plotting add_trace from within a function: Plotly

我試圖“功能化”我的情節陳述。 如果我想從另一個數據框中添加一條額外的軌跡,則會收到一個錯誤,即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

請注意, DateValuesValues2是全局環境中存在的對象。 因此, testfunction實際上是在對plot_ly的調用中使用這些對象。 為了說明這一點,請嘗試在plot_ly調用中刪除df -您仍然應該能夠獲得繪圖(即plot_ly實際上並未使用數據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)

這個問題和答案的提示:將變量作為參數傳遞給plot_ly函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM