簡體   English   中英

在 R Shiny 中顯示 Plotly 圖形

[英]Display Plotly graph in R Shiny

I am following the kmeans tutorial in the R Shiny Gallery and wanted to modify to use three variables and plot in a plotly 3D scatter. 沒有錯誤,但圖表未顯示。 這似乎應該工作......我做錯了什么?

data <- iris %>% select(-Species)

# this works
# data %>%
#   plot_ly(x = ~Petal.Length, y = ~Petal.Width, z = ~Sepal.Length) %>%
#   add_markers()

server = function(input, output, session) {

  # Combine the selected variables into a new data frame
  selectedData <- reactive({
    data[, c(input$xcol, input$ycol, input$zcol)]
  })

  clusters <- reactive({
    kmeans(selectedData(), input$clusters)
  })

  output$plot1 <- renderPlotly({
    selectedData() %>%
      plot_ly(x = ~input$xcol, y = ~input$ycol, z = ~input$zcol) %>%
      add_markers()
  })

}

ui <- 

  pageWithSidebar(
    headerPanel('Iris'),
    sidebarPanel(
      selectInput('xcol', 'X Variable', names(data)),
      selectInput('ycol', 'Y Variable', names(data)),
      selectInput('zcol', 'Z Variable', names(data)),
      numericInput('clusters', 'Cluster count', value = 3, step = .5, min = 1, max = 10)
    ),
    mainPanel(
      plotOutput('plot1')
    )
  )

# Run the application 
shinyApp(ui = ui, server = server)

要在 Shiny 中正確渲染 plotly output ,您需要使用plotlyOutput而不是plotOutput

關於使用用戶選擇輸入的子集數據幀,我傾向於首先存儲反應性 function 的 output,然后像我將子集任何其他 Z6A8064B5DF479455500553C47C555 一樣進行子集。 這樣,反應式 function 只被調用一次。

無論如何,更好地理解 shiny 的好資源是https://mastering-shiny.org/

希望這有幫助:)

library(shiny)
library(plotly)

data <- iris %>% select(-Species)

server = function(input, output, session) {

# I Combined the selected variables into a new data frame
# and added a new column with the cluster id assignated to each observation

selectedData <- reactive({
  res <- data[, c(input$xcol, input$ycol, input$zcol)]
  k <- kmeans(res, input$clusters)
  clusters <- k$cluster
  res$clusters <- clusters
  res
})

output$plot1 <- renderPlotly({
  df <- selectedData()
  plot_ly(x = df[, input$xcol], y = df[, input$ycol], z = df[, input$zcol],
        color = df$clusters) %>%
  add_markers()
})

}

ui <- pageWithSidebar(
 headerPanel('Iris'),
 sidebarPanel(
  selectInput('xcol', 'X Variable', names(data), selected = names(data)[1]),
  selectInput('ycol', 'Y Variable', names(data), selected = names(data)[2]),
  selectInput('zcol', 'Z Variable', names(data), selected = names(data)[3]),
  numericInput('clusters', 'Cluster count', value = 3, step = 1, min = 1, max = 10)
 ),
 mainPanel(
  plotlyOutput('plot1')
 )
)

# Run the application 
shinyApp(ui = ui, server = server)

暫無
暫無

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

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