繁体   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