【问题标题】:can stat_poly_eq() be added to plotly plot?可以将 stat_poly_eq() 添加到绘图中吗?
【发布时间】:2021-03-08 06:01:03
【问题描述】:

可以轻松地将stat_poly_eq() 包含在ggplot 中,但是有没有办法将其包含在plotly 图中?

当我尝试使用ggplotly 时,它不会呈现stat_poly_eq()

或者在plotly的情况下我应该使用不同的函数吗?

【问题讨论】:

    标签: r ggplot2 plotly ggplotly


    【解决方案1】:

    您可以使用 ggplotly 更改包含 stat_poly_eq 的 ggplot。新的 plotly 对象仍然得到多项式回归。

    工作示例:

    library(ggplot2)
    library(ggpmisc)
    library(plotly)
    set.seed(4321)
    x <- 1:100
    y <- (x + x^2 + x^3) + rnorm(length(x), mean = 0, sd = mean(x^3) / 4)
    my.data <- data.frame(x = x, y = y,
                          group = c("A", "B"),
                          y2 = y * c(0.5,2),
                          w = sqrt(x))
    
    # give a name to a formula
    formula <- y ~ poly(x, 3, raw = TRUE)
    
    # no weights
    p<-ggplot(my.data, aes(x, y)) +
       geom_point() +
       geom_smooth(method = "lm", formula = formula) +
       stat_poly_eq(formula = formula, parse = TRUE)
    
    ggplotly(p)
    

    唯一的区别是,您没有得到R^2 的文本框。我们对此无能为力,因为它尚未实施(11.2020),如错误消息所示。


    如果这仍然不适合您。您可以手动添加回归并将其添加到plotly。这取自现有的解决方案。检查here 给予学分。这种方式更容易修改,您可以添加所需的所有信息。

      library(plotly)
      library(dplyr)
      data(cars, package = "datasets")
    
     qfit1 <- lm(dist ~ poly(speed,2), data = cars)
    
      cars %>%     
      plot_ly() %>%  
      add_lines(x = ~speed, y = fitted(qfit1)) %>%
      add_trace(x=~speed, y=~dist)
    

    为您的 R 平方添加文本可能是:

      add_annotations(text= sprintf("R^2: %f", summary(qfit1)[8]), showarrow=FALSE, xref="paper", yref="paper", x=0.05,y=0.9)
    

    有关更多选项和自定义,请查看 add_annotaions 的文档。

    【讨论】:

    • 我需要在图上有 R^2 值。在 ggplot 中是可能的,但在 plotly 或 ggplotly 中是不可能的
    • @kolas0202 当您使用lm 计算它时,您可以在文本字段中添加 R^2。这就是我总结第二个解决方案的原因。
    • @kolas0202 我用一个例子插入了 R^2 值
    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2011-01-31
    • 2020-07-16
    相关资源
    最近更新 更多