r - 从 Shiny ggplot 中的点击创建数据集

标签 r ggplot2 shiny

我是一个 Shiny 的新手,但我正在尝试在我正在从事的项目中使用它。我希望能够通过点击 ggplot 图上的一个点来做两件事:在指定点添加一个绘图字符(以侧边栏的信息为条件),并将坐标(来自侧边栏的信息)添加到一个数据框。到目前为止,这是我在代码方面的内容:

library(shiny)
library(ggplot2)

df = data.frame()


ui = pageWithSidebar(
  headerPanel("Test"),

  sidebarPanel(
    radioButtons("orientation", "Pick", c("L", "P", "H")),

    selectInput(
      "select1",
      "Select Here:",
      c("Option 1", "Option 2")
    ),

    selectInput(
      "select2",
      "Select Here:",
      c("Option 3", "Option 4"),
    ),

    radioButtons("type", "Type:", c("P", "S")),

    radioButtons("creator", "Creator?", c("H", "A"))
  ),

  mainPanel(
    plotOutput("plot1", click = "plot_click"),
    verbatimTextOutput("info"),
    actionButton("update", "Add Event")
  )
)

server = function(input, output){

  output$plot1 = renderPlot({
    ggplot(df) + geom_rect(xmin = 0, xmax = 100, ymin = 0, ymax = 50, fill = "red")
  })

  output$info = renderText({
    paste0("x = ", input$plot_click$x, "\ny = ", input$plot_click$y)
  })
}

shinyApp(ui, server)

我对如何从 plot_click 添加点击的 x 和 y 点感到困惑至 df这样我就可以将数据添加到更大的数据库中。任何帮助将不胜感激,如果需要,我很乐意提供有关该项目的更多信息!

最佳答案

这是您可以使用的通用框架:

  • 使用 reactiveValues()x 设置一个带有列的响应式(Reactive) data.frame , y , inputs
  • 使用具有基于 input 的绘图特征的 react 性 data.frame 创建绘图
  • 单击绘图后,使用 observeEvent 向 react 性 data.frame 添加新行
  • (可选)添加 actionButton删除最后添加的点

  • 基于您的代码的简化示例如下。该表基于 this answer .

    enter image description here
    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"),
                            actionButton("rem_point", "Remove Last Point"),
                            plotOutput("plot1", click = "plot_click")),
                     column(width = 6,
                            h4("Table of points on plot"),
                            tableOutput("table")))
        )
    )
    
    server = function(input, output){
    
        ## 1. set up reactive dataframe ##
        values <- reactiveValues()
        values$DT <- data.frame(x = numeric(),
                                y = numeric(),
                                color = factor(),
                                shape = factor())
    
        ## 2. Create a plot ##
        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") +
                # include so that colors don't change as more color/shape chosen
                scale_color_discrete(drop = FALSE) +
                scale_shape_discrete(drop = FALSE)
        })
    
        ## 3. add new row to reactive dataframe upon clicking plot ##
        observeEvent(input$plot_click, {
            # each input is a factor so levels are consistent for plotting characteristics
            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")))
            # add row to the data.frame
            values$DT <- rbind(values$DT, add_row)
        })
    
        ## 4. remove row on actionButton click ##
        observeEvent(input$rem_point, {
            rem_row <- values$DT[-nrow(values$DT), ]
            values$DT <- rem_row
        })
    
        ## 5. render a table of the growing dataframe ##
        output$table <- renderTable({
            values$DT
        })
    }
    
    shinyApp(ui, server)
    

    关于r - 从 Shiny ggplot 中的点击创建数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49190820/

    相关文章:

    R将函数应用于数据框的子集

    r - 使用 purrr::map_df 转发函数中的参数

    r - 如何使用条件标签在循环中制作多个ggplots

    javascript - 将 sliderInput 值设置为 Shiny 的字符

    r - 是否有任何类似的方法来对 Shiny 中的 excel 中的多列进行条件格式设置

    r - 使用 dplyr 过滤 SQLite 数据库时,是否应该避免 `|`?

    r - 为因子内的 NA 值分配预定水平

    r - R : How to to get yaxis labels to use ticktext value instead of range value? 中带有 facet_grid 的 Plotly 和 ggplot

    r - 弹出模式内的 Shiny 模块化输入在关闭时不会被写入reactiveValues [flexdashboard/shinydashboard]

    r - 错误: cannot coerce type 'environment' to vector of type 'character'