英文:
Shiny: get x, y axis locations from a plot from multiple clicks
问题
以下是代码的翻译部分:
library(shiny)
ui <- basicPage(
plotOutput("plot1",
click = "plot_click",
hover = "plot_hover"
),
verbatimTextOutput("info")
)
server <- function(input, output) {
output$plot1 <- renderPlot({
plot(mtcars$wt, mtcars$mpg)
})
output$info <- renderText({
xy_str <- function(e) {
if(is.null(e)) return("NULL\n")
paste0("x=", round(e$x, 1), " y=", round(e$y, 1), "\n")
}
paste0(
"click: ", xy_str(input$plot_click),
"hover: ", xy_str(input$plot_hover)
)
})
}
shinyApp(ui, server)
希望这个翻译对您有所帮助。
英文:
The below code show how to get the x, y axis location from one click.
How can I get x, y axis locations from multiple clicks on the plot?
library(shiny)
ui <- basicPage(
plotOutput("plot1",
click = "plot_click",
hover = "plot_hover"
),
verbatimTextOutput("info")
)
server <- function(input, output) {
output$plot1 <- renderPlot({
plot(mtcars$wt, mtcars$mpg)
})
output$info <- renderText({
xy_str <- function(e) {
if(is.null(e)) return("NULL\n")
paste0("x=", round(e$x, 1), " y=", round(e$y, 1), "\n")
}
paste0(
"click: ", xy_str(input$plot_click),
"hover: ", xy_str(input$plot_hover)
)
})
}
shinyApp(ui, server)
答案1
得分: 2
我添加了一个反应式值 rv_click$tb
来记录点击事件。同时添加了一个重置按钮,用于重置操作。
英文:
Try this:
library(shiny)
library(dplyr)
ui <- basicPage(
plotOutput("plot1",
click = "plot_click",
hover = "plot_hover"
),
actionButton("reset", "reset", class = "btn-warning"),
verbatimTextOutput("info")
)
server <- function(input, output) {
rv_click <- reactiveValues(tb = tibble(x = double(), y = double()))
observeEvent(input$reset, {
rv_click$tb <- tibble(x = double(), y = double())
})
observeEvent(input$plot_click, {
rv_click$tb <-
isolate(rv_click$tb) %>%
add_row(
x = input$plot_click$x,
y = input$plot_click$y
)
})
output$plot1 <- renderPlot({
plot(mtcars$wt, mtcars$mpg)
})
output$info <- renderText({
tb_click <- rv_click$tb
if (nrow(tb_click) == 0L) return("Please click on the plot.")
paste0(
"click: ", sprintf("%02d", 1:nrow(tb_click)), " ",
"x: ", round(tb_click$x, 1), " ",
"y: ", round(tb_click$y, 1), "\n"
)
})
}
shinyApp(ui, server)
I added a reactive value rv_click$tb
to record the click event. Also a reset button to, you know, reset.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论