【发布时间】:2021-03-08 06:01:03
【问题描述】:
可以轻松地将stat_poly_eq() 包含在ggplot 中,但是有没有办法将其包含在plotly 图中?
当我尝试使用ggplotly 时,它不会呈现stat_poly_eq()。
或者在plotly的情况下我应该使用不同的函数吗?
【问题讨论】:
可以轻松地将stat_poly_eq() 包含在ggplot 中,但是有没有办法将其包含在plotly 图中?
当我尝试使用ggplotly 时,它不会呈现stat_poly_eq()。
或者在plotly的情况下我应该使用不同的函数吗?
【问题讨论】:
您可以使用 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 的文档。
【讨论】:
lm 计算它时,您可以在文本字段中添加 R^2。这就是我总结第二个解决方案的原因。