在 R Shiny 中显示 Plotly 图

Display Plotly graph in R Shiny

我正在关注 R Shiny Gallery 中的 kmeans 教程,并希望修改为使用三个变量并在 plotly 3D 散点图中绘制。没有错误,但图形未显示。这似乎应该有效...我做错了什么?

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 输出,您需要使用 plotlyOutput 而不是 plotOutput

关于使用用户选择的输入对数据帧进行子集化,我倾向于首先存储反应函数的输出,然后像对任何其他数据帧进行子集化一样进行子集化。这样,反应函数只被调用一次。

无论如何,更好地理解 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)