【问题标题】:How to make a shiny app that allows to draw multiple polygons on raster images?如何制作一个允许在光栅图像上绘制多个多边形的闪亮应用程序?
【发布时间】:2021-12-21 23:20:21
【问题描述】:

我想开发一个shiny 应用程序,用户可以在其中在raster 图像上绘制多边形。用户绘制完多边形后,我希望应用程序向他们显示所选像素的表格。

例如,terra 提供了一个函数draw,可以用作draw("polygon")。但是,我无法让它与我的 shiny 应用程序一起使用。

app的基本思路如下(有问题的部分我已经用#注释掉了):

library(terra)
library(shiny)

r = rast(system.file("ex/elev.tif", package="terra"))

ui = fluidPage(
        plotOutput("map"),
        tableOutput("chosen_pixels")
)

server = function(input, output, session) {
        output$map = renderPlot({
                plot(r)
                # draw("polygon") # I comment it otherwise the app does not run
        })
        
        # output$chosen_pixels = renderPlot({
                # here I want to write code that shows a table of chosen pixels
        #})
}

shinyApp(ui, server)

【问题讨论】:

    标签: r shiny raster r-raster terra


    【解决方案1】:
    library(shiny)
    library(tidyverse)
    
    ui <- basicPage(
      plotOutput("plot1", click = "plot_click"),
      tableOutput("table"),
      textInput("polygon_name", label = "Polygon name", value = "polygon 1")
    )
    
    server <- function(input, output) {
      coords <- reactiveVal(value = tibble(x = numeric(), y = numeric(), name = character()))
    
      observeEvent(input$plot_click, {
        add_row(coords(),
          x = isolate(input$plot_click$x),
          y = isolate(input$plot_click$y),
          name = isolate(input$polygon_name)
        ) %>% coords()
      })
    
      output$plot1 <- renderPlot({
        plot(r)
        
        coords() %>%
          nest(-name) %>%
          deframe() %>%
          map(~ polygon(.x$x, .x$y))
      })
    
      output$table <- renderTable(coords())
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    • 这是一个非常好的方法!目前我无法逃脱绘制的多边形。有没有办法“刷新”它,以便用户可以在其他地方开始制作新的多边形?
    • @bird 我添加了一个新输入来命名多边形。每当名称更改时,都会创建一个新的多边形。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多