我正在为一个项目开发一个Shiny应用程序,其中ggplot是用户的主要界面。根据侧边栏的输入,我希望应用程序记录两个事件的坐标:单击(我工作)或双击(这是我被困的地方)。基本上,我希望能够创建一种基于侧边栏条件记录起点和终点的方法。这是一个简短的例子:
library(shiny)
library(ggplot2)
ui = pageWithSidebar(
headerPanel("Example"),
sidebarPanel(
radioButtons("color", "Pick Color", c("Pink", "Green", "Blue")),
selectInput("shape", "Select Shape:", c("Circle", "Triangle"))
),
mainPanel(
fluidRow(column(width = 6,
h4("Click plot to add points"),
plotOutput("plot1", click = "plot_click"),
actionButton("rem_point", "Remove Last Point")),
column(width = 6,
h4("Table of points on plot"),
tableOutput("table")))
)
)
server = function(input, output){
values = reactiveValues()
values$DT = data.frame(x = numeric(),
y = numeric(),
color = factor(),
shape = factor())
output$plot1 = renderPlot({
ggplot(values$DT, aes(x = x, y = y)) +
geom_point(aes(color = color,
shape = shape), size = 5) +
lims(x = c(0, 100), y = c(0, 100)) +
theme(legend.position = "bottom") +
scale_color_discrete(drop = FALSE) +
scale_shape_discrete(drop = FALSE)
})
observeEvent(input$plot_click, {
add_row = data.frame(x = input$plot_click$x,
y = input$plot_click$y,
color = factor(input$color, levels = c("Pink", "Green", "Blue")),
shape = factor(input$shape, levels = c("Circle", "Triangle")))
values$DT = rbind(values$DT, add_row)
})
observeEvent(input$rem_point, {
rem_row = values$DT[-nrow(values$DT), ]
values$DT = rem_row
})
output$table = renderTable({
values$DT[, c('color', 'shape')]
})
}
shinyApp(ui, server)
在此示例中,当用户选择绿色或蓝色时,我只想记录单击作为起点并记录终点NA
。当他们选择粉红色时,我想记录单击作为起点,双击作为结束点。任何帮助将不胜感激!
(由a question from earlier上的@blondeclover创建的示例。)
答案 0 :(得分:0)
找到解决方案!只需创建observeEvent()
即可观察双击并使用新信息更新values$DT
。