使用ggplotly在交互式回归图中正确标注回归方程的方法
问题:ggplotly中无法正常显示回归方程
我在开发Shiny应用,需要绘制带交互性的回归图(支持悬停查看数据点),使用ggplotly实现时,遇到回归方程无法正常兼容显示的问题。
原问题代码
library(ggplot2) library(plotly) library(ggpubr) df <- data.frame(x = c(1:100)) df$y <- 2 + 3 * df$x + rnorm(100, sd = 40) df$yy <- 2 + 3 * df$x + 0.1 * df$x^2 + rnorm(100, sd = 40) p <- ggplot(data = df, aes(x = x, y = y)) + geom_point()+ geom_smooth(method = "lm")+ stat_regline_equation(aes(label = paste(..eq.label..,..adj.rr.label.., sep = "~~~~"))) ggplotly(p, dynamicTicks = TRUE)
问题原因
原代码中ggpubr::stat_regline_equation生成的回归方程是表达式(expression)类型,而ggplotly对表达式格式的文本渲染支持有限,导致方程无法正常显示。
解决代码
library(plotly) library(ggpubr) library(ggpmisc) library(ggplot2) df <- data.frame(x = c(1:100)) df$y <- 2 + 3 * df$x + rnorm(100, sd = 40) df$yy <- 2 + 3 * df$x + 0.1 * df$x^2 + rnorm(100, sd = 40) my.formula <- y ~ x p <- ggplot(data = df, aes(x = x, y = y)) + geom_smooth(method = "lm", formula = my.formula)+ stat_poly_eq(geom = "text", # 覆盖默认的"text_npc" output.type = "text", # 覆盖默认的"expression",输出纯文本 formula = my.formula, aes(label = paste(..eq.label.., ..rr.label.., sep = ", ")), label.x = 20) + # 手动指定方程显示位置 geom_point() ggplotly(p, dynamicTicks = TRUE)
关键修改说明
- 替换标注函数:用
ggpmisc::stat_poly_eq替代stat_regline_equation,该函数支持输出纯文本格式的方程 - 输出格式设置:通过
output.type = "text"将方程转为纯文本,确保ggplotly能正确渲染 - 显式指定公式:定义
my.formula统一回归公式,避免参数不一致 - 位置控制:使用
label.x手动调整方程的显示位置,适配图表布局
内容的提问来源于stack exchange,提问作者Todd
相关产品推荐
相关产品推荐

