簡體   English   中英

在R的Shiny App中動態繪制繪圖

[英]Plot the Plotly Graph Dynamically in the Shiny App in R

我想在R的Shiny App中繪制一個Plotly圖。我想要這種功能,以便在一個循環中繪制一定數量的點(例如20)。

這是我的Server.R代碼:

xAxis = vector("numeric", as.numeric(input$Generations))
yAxis = vector("numeric", as.numeric(input$Generations))

graphDF = data.frame(cbind(xAxis, yAxis))

for(i in 1 : 5)
{    output$GA = renderPlotly({

  print(graphDF) # Testing 

  graphDF$yAxis[i] = i
  graphDF$xAxis[i] = i

  print(graphDF) # Testing

  # Plotly functionality
  p <- plot_ly(graphDF, x = graphDF$xAxis, y = graphDF$yAxis)

})
}

非常感激任何的幫助。

親切的問候

這比看起來要復雜。 您似乎想要迭代並創建一系列繪圖圖,並在操作時更改數據值。

由於“ Generations滑塊將向量重新初始化為新的長度,並且每次迭代都會更改要繪制的數據的狀態,因此,您不僅可以級聯反應函數。 將狀態存儲在reactiveValues是處理此問題的好方法。

主要變化如下:

  • 增加了一個reactiveValues存儲xAxisyAxis
  • 添加了一個observeEvent以在其值更改時重新初始化這些值
  • 添加了“迭代范圍”滑塊來驅動迭代(比反應式計時器更容易)。 請注意,它有一個animate參數,(可能)自己創建了一個反應式計時器。
  • 修改了plotly調用,使其更加常規並避免了警告。

編碼:

library(shiny)
library(plotly)

u <- fluidPage(
  titlePanel("Iterations of a plotly graph"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("Generations","Number of Generations:",
                  min = 1,  max = 50,  value = 20),
      sliderInput("iter", "Iteration range:", 
                  value = 1,  min = 1,  max = 1000, step = 1,
                  animate=animationOptions(interval=800, loop=T)),
      p("To start click on the blue arrowhead")
    ),
    mainPanel(
      plotlyOutput("GA")
    )
))
s <- shinyServer(function(input,output){

  rv <- reactiveValues(xAxis=NULL,yAxis=NULL)

  observeEvent(input$Generations,{
    rv$xAxis=vector("numeric", as.numeric(input$Generations))
    rv$yAxis=vector("numeric", as.numeric(input$Generations))
  })
  output$GA = renderPlotly({
      rv$yAxis[input$iter] <- input$iter 
      rv$xAxis[input$iter] <- input$iter
      gdf <- data.frame(xAxis=rv$xAxis, yAxis=rv$yAxis)
      plot_ly(gdf, x = ~xAxis, y = ~yAxis, type="scatter",mode="markers")
    })
})
shinyApp(u,s)

因為它是動態的,所以您必須運行它以查看其實際工作原理,但是下面是經過多次迭代的屏幕截圖:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM