首页 > 解决方案 > 如何在R中改变闪亮的曲线

问题描述

我想更改数字以使情节动画化。我试过这个

library(shiny)
library(ggplot2)
ui <- fluidPage(
  titlePanel("Equation"),
  sidebarLayout(
    sidebarPanel(
      sliderInput(inputId = "values",
                  label = "number of values:",
                  min = -5,
                  max = 5,
                  value = 5)
    ),
    mainPanel(
      plotOutput(outputId = "distPlot")
    )
  )
)
server <- function(input, output) {
  output$distPlot <- renderPlot({
    k <- function(x,c) { 
      p <- (-x^3+c)
      return(p)
    } 
    gg <- function(c_val) {
      ggplot(data.frame(x = c(-50, 50)), aes(x)) +
        stat_function(fun = k, args = list(c=c_val), aes(colour = "temp"))}
    gg(-5)
  })
}
shinyApp(ui,server)

我可以看到情节和侧边栏,但是当我移动侧边栏时,它不会改变。我努力改变剧情。我知道它可能不会发生重大变化,但对于这些代码的目的来说并不重要。

我想知道我们是否可以使用闪亮来做到这一点。

标签: rggplot2shiny

解决方案


您需要为您的 ggplot 提供输入:替换gg(-5)gg(input$values). 正如评论中所说,由于您的滑块只是更改曲线的偏移量,因此您需要适当的比例来查看更改。我将其设置为 -5:5:

library(shiny)
library(ggplot2)
ui <- fluidPage(
  titlePanel("Equation"),
  sidebarLayout(
    sidebarPanel(
      sliderInput(inputId = "values",
                  label = "number of values:",
                  min = -5,
                  max = 5,
                  value = 5)
    ),
    mainPanel(
      plotOutput(outputId = "distPlot")
    )
  )
)
server <- function(input, output) {
  output$distPlot <- renderPlot({
    k <- function(x,c) { 
      p <- (-x^3+c)
      return(p)
    } 
    gg <- function(c_val) {
      ggplot(data.frame(x = c(-5, 5)), aes(x)) +
        stat_function(fun = k, args = list(c=c_val), aes(colour = "temp"))}
    gg(input$values)
  })
}
shinyApp(ui,server)

推荐阅读