我的目标是构建一个简单的ShinyApp,它允许用户通过在shiny::textInput中键入公式(例如x^2)来在曲线图上显示特定的单变量函数.我试着用ggplot2::stat_funcion来解决这个问题,但不幸的是,从那以后我一直没能找到解决方案.

My code

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

  ui <- dashboardPage(
    
          dashboardHeader(title = h4(HTML("Title<br/>Subtitle"))),
          
          dashboardSidebar(textInput("function1", "Function")),
          
          dashboardBody(
            fluidRow(box(title = h4(HTML("Chart title")),
                         plotlyOutput("chart", height = 250)))
          )
          
        )
   
  
  server <- function(input, output) {
    
    MyFunction <- function(x) {x}
    func <- reactive({MyFunction(input$function1)}) 
    
    output$chart <- renderPlotly({
      
                    ggplotly(
                      chart = ggplot(data.frame(x = c(0, 15)), aes(x)) +
                        stat_function(fun = func, 
                                      geom = "line", size = 1, show.legend = F) + 
                        scale_x_continuous(limits = c(-100, 100)) 
                    )
                
                    })
    
  }
  
  shinyApp(ui, server)

我感谢任何帮助!先谢谢你了!

推荐答案

文本输入需要转换为表达式并求值

eval(parse(text = input$function1))

否则它只是一个字符串.

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

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


server <- function(input, output) {
  output$chart <- renderPlotly({
    ggplotly(
      p = ggplot(data.frame(x = c(0, 15)), aes(x)) +
        stat_function(
          fun = function(x) eval(parse(text = input$function1)),
          geom = "line", size = 1, show.legend = F
        ) +
        scale_x_continuous(limits = c(-100, 100))
    )
  })
}

shinyApp(ui, server)

R相关问答推荐

根据固定值范围在tible中添加新行

创建重复删除的唯一数据集组合列表

使用预定值列表将模拟数量(n)替换为rnorm()

在通过最大似然估计将ODE模型与数据匹配时,为什么要匹配实际参数的转换值?

geom_Ribbon条件填充创建与数据不匹配的形状(ggplot 2 r)

R Markdown中的交叉引用表

使用case_match()和char数组重新编码值

如何计算多个日期是否在一个日期范围内

在嵌套列表中查找元素路径的最佳方法

随机森林的带Shap值的蜂群图

从R中发出的咕噜声中的BUG?

R代码,用于在线条图下显示观测表

错误包arrowR:READ_PARQUET/OPEN_DATASET&QOT;无法反序列化SARIFT:TProtocolException:超出大小限制&Quot;

名字的模糊匹配

替换在以前工作的代码中有x行&q;错误(geom_sf/gganimate/dow_mark)

使用LAG和dplyr执行计算,以便按行和按组迭代

如何在shiny 的应用程序 map 视图宣传单中可视化单点

条形图中的条形图没有try 赋予它们的 colored颜色

在分面的ggplot2条形图中对条形图进行排序,并省略每组未使用的系数级别

如何将两个用不同的运算符替换*的矩阵相乘