【问题标题】:Remembering Selected Points on Plot in Shiny在 Shiny 中记住情节上的选定点
【发布时间】:2017-01-18 23:14:33
【问题描述】:

我正在尝试创建一个交互式 k-means 图,它可以让人们看到他们输入的效果(比如指定中心而不是纯粹的随机选择),但我的 Shiny 代码遇到了问题。我试图了解如何选择一个点并让我的应用记住它以用作中心。我一直在寻找一种使用反应式代码来做到这一点的方法,但到目前为止我尝试过的一切都失败了。我目前的工作代码如下:

# Pre Work
library(ggfortify)
dsnames <- names(iris[1:4])
cb_options <- list()
cb_options[dsnames] <- dsnames

# UI
shinyUI <- fluidPage(
  titlePanel("Interactive K-Means Clustering Using Iris Dataset"),
  sidebarPanel(
    numericInput("numCenter", label=h4("Centers for k-means:"), min=2, max=30, value=3),
    selectInput("xaxisGrp","X-Axis:", c("1"="1","2"="2"), choices=cb_options),
    selectInput("yaxisGrp","Y-Axis:", c("1"="1","2"="2"), choices=cb_options),
    tableOutput("info")
  ),
  mainPanel(
    plotOutput("plot1", click="plot_click", dblclick="plot_dbl")
  )
)

# Server
shinyServer <- function(input, output, session) {

  iris_k <- reactive({
    kmeans(iris[1:4], centers=input$numCenter)
  })

  output$plot1 <- renderPlot({
    ggplot() + geom_point(data=iris, aes_string(input$xaxisGrp, input$yaxisGrp), colour=iris_k()$cluster)
  })

  output$info <- renderTable({
    nearPoints(iris, input$plot_click, xvar=input$xaxisGrp, yvar=input$yaxisGrp)[,c(input$xaxisGrp, input$yaxisGrp)]
  })

}

# ShinyApp function call
shinyApp(ui=shinyUI, server=shinyServer)

我怎样才能做到这一点?

【问题讨论】:

    标签: r plot shiny


    【解决方案1】:

    嗯,在我的工作代码中发现了一些缺陷后,我设法解决了这个问题。如果这个答案对其他人有帮助,我会很高兴。新的 Shiny Server 代码使用了 reactiveValues(),因为我误解了它们的用法,它以前没有用过。新的代码段是:

       v <- reactiveValues(
         selectedData = NULL
         )
    
       observeEvent(input$plot_dbl, {
         X1 <- nearPoints(iris, input$plot_dbl)
         if (is.null(v$selectedData)) {
           v$selectedData <- X1
         } else {
           if (nrow(merge(X1, v$selectedData)) > 0) {
             ind <- anyDuplicated(rbind(v$selectedData, X1), fromLast=TRUE)
             v$selectedData <- v$selectedData[-ind,]
           } else {
             v$selectedData <- rbind(v$selectedData, X1)
           }
         }
       })
    

    这让我可以在图表上选择绘制点并按我的意愿记住它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多