Shiny应用点击趋势线无数据坐标点时崩溃问题求助
嘿,我帮你搞定这个Shiny应用崩溃的问题啦!咱们先理清楚问题根源,再给出具体的修复方案:
问题复现
首先我补全了你提供的不完整代码,这样能完整复现点击趋势线空白点崩溃的情况:
# ui.r library(shiny) library(ggplot2) library(plotly) library(dplyr) fluidPage( titlePanel("mtcars Scatter Plot with Model Names"), sidebarLayout( sidebarPanel( selectInput("x_var", "X Variable:", choices = names(mtcars)), selectInput("y_var", "Y Variable:", choices = names(mtcars)) ), mainPanel( plotlyOutput("scatter_plot") ) ) ) # server.r function(input, output) { output$scatter_plot <- renderPlotly({ p <- ggplot(mtcars, aes(x = .data[[input$x_var]], y = .data[[input$y_var]], text = rownames(mtcars))) + geom_point() + geom_smooth(method = "lm", se = FALSE) + labs(x = input$x_var, y = input$y_var) ggplotly(p, tooltip = "text") }) }
问题根源
崩溃的原因很简单:你把text(车型名)绑定到了整个ggplot的aes里,导致趋势线也继承了这个映射,但趋势线的计算点没有对应的车型名数据。当你点击趋势线上的点时,plotly试图读取不存在的text值,直接触发了错误。
修复方案
这里给你两种实用的解决办法,按需选择:
方案一:彻底禁用趋势线的交互性
如果你只希望用户和实际数据点交互,完全屏蔽趋势线的点击/hover事件,修改server端代码如下:
output$scatter_plot <- renderPlotly({ p <- ggplot(mtcars, aes(x = .data[[input$x_var]], y = .data[[input$y_var]], text = rownames(mtcars))) + geom_point() + geom_smooth(method = "lm", se = FALSE) + labs(x = input$x_var, y = input$y_var) # 转换为plotly对象后,找到趋势线的trace(通常是第2个,索引从0开始) fig <- ggplotly(p, tooltip = "text") # 禁用hover和点击事件 fig$x$data[[1]]$hoverinfo <- "none" fig$x$data[[1]]$clickmode <- "none" fig })
方案二:给趋势线设置默认tooltip
如果想保留趋势线的hover效果,又不想崩溃,可以给趋势线单独设置一个默认的tooltip文本,避免读取空数据:
output$scatter_plot <- renderPlotly({ p <- ggplot(mtcars, aes(x = .data[[input$x_var]], y = .data[[input$y_var]])) + # 仅给数据点绑定车型名text geom_point(aes(text = rownames(mtcars))) + # 给趋势线设置默认的tooltip内容 geom_smooth(method = "lm", se = FALSE, aes(text = "Linear Trend Line")) + labs(x = input$x_var, y = input$y_var) ggplotly(p, tooltip = "text") })
这两种方法都能解决点击趋势线崩溃的问题,你可以根据自己的需求选择~
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

