You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ShinyApp中通过输入公式动态生成stat_function函数图像?

解决ShinyApp中用户输入函数公式并绘图的问题

问题核心

原代码未将用户输入的字符串公式转换为可执行的函数,且stat_function的fun参数无法直接使用reactive对象,导致绘图功能失效。

修改后的完整代码

library(tidyverse)
library(plotly)
library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = h4(HTML("Title<br/>Subtitle"))),
  dashboardSidebar(textInput("function1", "Function", placeholder = "例如: x^2, sin(x)")),
  dashboardBody(
    fluidRow(box(title = h4(HTML("Chart title")),
                 plotlyOutput("chart", height = 250)))
  )
)

server <- function(input, output) {
  
  # 生成可执行函数,处理空输入的默认情况
  func <- reactive({
    if (input$function1 == "") {
      # 默认显示y=x
      function(x) x
    } else {
      # 将输入字符串解析为以x为参数的函数
      eval(parse(text = paste0("function(x) {", input$function1, "}")))
    }
  }) 
  
  output$chart <- renderPlotly({
    ggplotly(
      ggplot(data.frame(x = seq(-100, 100, length.out = 1000)), aes(x)) +
        stat_function(fun = func(),  # 调用reactive返回的函数对象
                      geom = "line", size = 1, show.legend = FALSE) + 
        scale_x_continuous(limits = c(-100, 100)) +
        scale_y_continuous(limits = c(-100, 100))  # 限制y轴范围,避免极端值导致图表异常
    )
  })
  
}

shinyApp(ui, server)

关键修改说明

  • 公式转函数:通过eval(parse(text = ...))将用户输入的字符串(如x^2)包装成R可执行的函数,让stat_function能直接调用绘图。
  • 空输入处理:当用户未输入内容时,自动使用默认的y=x函数,避免程序报错。
  • 平滑绘图:用seq(-100, 100, length.out = 1000)生成1000个x轴数据点,保证曲线平滑且覆盖设定的x轴范围。
  • y轴限制:添加scale_y_continuous限制y轴范围,防止用户输入x^3这类函数时,因数值过大导致图表显示异常。

内容的提问来源于stack exchange,提问作者Jannn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 19:40:00