【问题标题】:Display the count of clicks in a plot using shiny使用 shiny 显示图中的点击次数
【发布时间】:2022-11-18 21:38:01
【问题描述】:

我想构建一个闪亮的应用程序来计算我在任何图像上所做的点击次数,但我不知道如何使计数器增加,它只是绘制数字 1

我试图在 renderPlot 中创建循环,但它不起作用。

有必要将文件的路径更改为包含 .jpg 图像的目录

library(shiny)

ui <- fluidPage(

  titlePanel("Click Count"),

  sidebarPanel(selectInput("IMAGE", "Sample image:",
                           list.files(path = "~",
                                      pattern = ".jpg",
                                      full.names = TRUE,
                                      include.dirs = FALSE))),

  fluidRow(

    plotOutput("IMG", click = "countClick", "100%", "500px")
  ),

  verbatimTextOutput("info")
)

server <- function(input, output, session){


  # Creating a reactive variable that recognizes the selected image
  img <- reactive({
    f <- input$IMAGE
    imager::load.image(f)
  })

  # Creating a spot where i can store reactive values
  initX <- 1
  initY <- 2

  source_coords <- reactiveValues(xy = c(x=initX,y=initY))

  # Coords
  dest_coords <- reactiveValues(x=initX, y = initY)
  observeEvent(plot_click(),{
    dest_coords$x <- c(dest_coords$x, floor(plot_click()$x))
    dest_coords$y <- c(dest_coords$y, floor(plot_click()$y))
  })

  plot_click <- debounce(reactive(input$countClick), 300)

  output$IMG <- renderPlot({
    plot(img(), axes = FALSE)
    n <- 0
    ex <- expression(n+1)
    text(dest_coords$x, dest_coords$y,eval(ex),cex = 1 ,col = 'red')
  })

  output$info <- renderPrint({
    req(input$countClick)
    x <- round(input$countClick$x,2)
    y <- round(input$countClick$y,2)
    cat("[", x, ", ", y, "]", sep = "")
  })
}

shinyApp(ui, server)

【问题讨论】:

    标签: r shiny reactive-programming shinydashboard


    【解决方案1】:

    countClick 不是一个好名字,因为input$countClick 不包含点击次数。

    未测试:

      numberOfClicks <- reactiveVal(0)
      dest_coords <- reactiveValues(x = initX, y = initY)
      observeEvent(plot_click(),{
        numberOfClicks(numberOfClicks() + 1)
        dest_coords$x <- c(dest_coords$x, floor(plot_click()$x))
        dest_coords$y <- c(dest_coords$y, floor(plot_click()$y))
      })
    
      plot_click <- debounce(reactive(input$countClick), 300)
    
      output$IMG <- renderPlot({
        plot(img(), axes = FALSE)
        n <- numberOfClicks()
        text(dest_coords$x, dest_coords$y, n, cex = 1 ,col = 'red')
      })
    

    【讨论】: