2017-02-20 23 views
0

我想在R中的plot_ly()周圍編寫一個自定義函數。這樣,​​我可以使用一系列散點圖相同的格式和樣式,但不重複的代碼。 I used this page as a guide.此代碼再現錯誤:使用add_lines()擬合(lm(y〜x))的plot_ly()附近的自定義R函數

library(plotly) 
my_plot <- function(x, y, ...) { 
    require(broom) 
    plot_ly(data = mtcars, y = y, x = x, showlegend = FALSE, ...) %>% 
    add_markers(y = y) %>% 
    add_lines(y = ~fitted(lm(y ~ x))) %>% 
    add_ribbons(data = augment(lm(y ~ x, data = mtcars)), 
       ymin = ~.fitted - 1.96 * .se.fit, 
       ymax = ~.fitted + 1.96 * .se.fit, 
       line = list(color = 'rgba(7, 164, 181, 0.05)'), 
       fillcolor = 'rgba(7, 164, 181, 0.2)', 
       name = "Standard Error") 
} 
my_plot(y = ~mpg, x = ~disp) 

問題行是:

add_lines(y = ~fitted(lm(y ~ x))) %>% 

我嘗試使用as.formula(),但該錯誤消息是類似的。

add_lines(y = ~fitted(lm(as.formula("y ~ x"))) %>% 

以下是錯誤消息:

Error in model.frame.default(formula = y ~ x, data = mtcars, drop.unused.levels = TRUE) : object is not a matrix

代碼工作時,它不是一個功能:

library(plotly) 
library(broom) 
plot_ly(data = mtcars, y = ~mpg, x = ~disp, showlegend = FALSE) %>% 
    add_markers(y = ~mpg) %>% 
    add_lines(y = ~fitted(lm(mpg ~ disp))) %>% 
    add_ribbons(data = augment(lm(mpg ~ disp, data = mtcars)), 
      ymin = ~.fitted - 1.96 * .se.fit, 
      ymax = ~.fitted + 1.96 * .se.fit, 
      line = list(color = 'rgba(7, 164, 181, 0.05)'), 
      fillcolor = 'rgba(7, 164, 181, 0.2)', 
      name = "Standard Error") 

回答

0

可能性之一是通過這兩個數據框和列名字到你的功能,例如

library(plotly) 

my_plot <- function(data, x, y, ...) { 
    require(broom) 
    plot_ly(y = data[[y]], x = data[[x]], showlegend = FALSE, ...) %>% 
    add_markers(y = data[[y]]) %>% 
    add_lines(y = ~fitted(lm(data[[y]] ~ data[[x]]))) %>% 
    add_ribbons(data = augment(lm(data[[y]] ~ data[[x]])), 
       ymin = ~.fitted - 1.96 * .se.fit, 
       ymax = ~.fitted + 1.96 * .se.fit, 
       line = list(color = 'rgba(7, 164, 181, 0.05)'), 
       fillcolor = 'rgba(7, 164, 181, 0.2)', 
       name = "Standard Error") 
} 
my_plot(data = mtcars, y = 'mpg', x = 'disp') 

或只是列本身。

library(plotly) 

my_plot <- function(x, y, ...) { 
    require(broom) 
    plot_ly(y = y, x = x, showlegend = FALSE, ...) %>% 
    add_markers(y = y) %>% 
    add_lines(y = ~fitted(lm(y ~ x))) %>% 
    add_ribbons(data = augment(lm(y ~ x)), 
       ymin = ~.fitted - 1.96 * .se.fit, 
       ymax = ~.fitted + 1.96 * .se.fit, 
       line = list(color = 'rgba(7, 164, 181, 0.05)'), 
       fillcolor = 'rgba(7, 164, 181, 0.2)', 
       name = "Standard Error") 
} 
my_plot(y = mtcars$mpg, x = mtcars$disp) 
相關問題