R: An interactive graph of a function with sliders in plotly

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-29 09:20:35

问题


To plot a function with its parameters being updated dynamically via sliders is easy in R using basic plot and 'manipulate' package.
Here is an example of a sine wave with its amplitude and frequency being controlled by parameters A and k, respectively.

library(manipulate)
manipulate(plot(x, A*sin(k*x)), A = slider(1,3), k = slider(1,10))

However, the basic plot is not as pretty a plotly one. Is there a simple way to do it in plotly?

Plotly provides examples of sliders on its site, but the code seems too complex for such a simple task. If plotly does not provide a one or two liner for such tasks, are there other ways to do so in R?


回答1:


Here is a quick and dirty shiny app that does it based on one of the examples in the documentation and runs well from RStudio. Lots of opportunity to clean up the code especially in the renderPlot, but this will give you a starting point.

library(shiny)
library(shinydashboard)
library(ggplot2)

data <-  data.frame(x=c(1,2,3,4),y=c(10,11,12,13))
ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(sliderInput("sliderA","A", min=1, max=3, step=0.5, value=1),
               sliderInput("sliderK","K", min=1, max=10, step=1, value=1)),
  dashboardBody(
    fluidRow(column(6,plotOutput('waveplot')))
  ))

server <- function(input, output, session) { 
  output$waveplot <- renderPlot({
    x <- seq(0,10,0.1)
    yfxn <- function(x) { input$sliderA*sin(input$sliderK*x) }
    y <- yfxn(x)
    df <- data.frame(x,y)
    ggplot(df,aes_string(x=x,y=y))+geom_point(size=2)+geom_line()+ 
         scale_x_continuous()
  })
}

shinyApp(ui, server)



来源:https://stackoverflow.com/questions/53199645/r-an-interactive-graph-of-a-function-with-sliders-in-plotly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!