使用R Shiny默认显示所有数据点

问题描述 投票:0回答:1

我想使用 R Shiny 绘制一些数据点的空间分布图。当我将不同区域的过滤器添加到 R 脚本中时,它无法在默认地图上显示所有区域的所有数据点。

对于如何改进脚本有什么建议吗?

下面是我的 R 脚本和示例数据:

library(shiny)
library(shinythemes)
library(leaflet)

# generate the data
dat <- data.frame(
  region=sample(c("A","B","C"),100,replace=T),
  x=rnorm(100, mean=50, sd=10),
  y=rnorm(100, mean=40, sd=10)
)

# Define UI for application that draws a histogram
ui <- shinyUI(fluidPage(
  theme = shinytheme("united"),
  # Application title
  titlePanel("Test"),
  
  # Sidebar
  sidebarLayout(
    sidebarPanel(
      selectizeInput(
        "regionInput", label=h3("Region"),choices=c("A","B","C"))
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      leafletOutput(outputId = 'map')
    )
  )
)
)

# Define server logic to map the distribution
server <- shinyServer(function(input, output) {
  
  output$map <- renderLeaflet({
    leaflet(dat) %>%
      addProviderTiles("Esri.WorldImagery") %>%
      addCircleMarkers(color = "blue", radius = 2, stroke = FALSE, fillOpacity = 0.5, lng=dat$x[which(dat$region == input$regionInput)], lat=dat$y[which(dat$region == input$regionInput)])
  })
  
  
})

# Run the application 
shinyApp(ui = ui, server = server)
r shiny leaflet
1个回答
0
投票

您需要在下拉列表中添加一个

(All)
元素,并在渲染函数中添加逻辑,如下所示:

library(shiny)
library(shinythemes)
library(leaflet)

# generate the data
dat <- data.frame(
  region = sample(c("A", "B", "C"), 100, replace = TRUE),
  x = rnorm(100, mean = 50, sd = 10),
  y = rnorm(100, mean = 40, sd = 10)
)

# Define UI for application that draws a histogram
ui <- fluidPage(
  theme = shinytheme("united"),
  # Application title
  titlePanel("Test"),
  
  # Sidebar
  sidebarLayout(
    sidebarPanel(
      selectizeInput(
        "regionInput", 
        label = h3("Region"),
        choices = c("(All)", "A", "B", "C"))
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      leafletOutput(outputId = "map")
    )
  )
)


# Define server logic to map the distribution
server <- shinyServer(function(input, output) {
  
  output$map <- renderLeaflet({
    if (input$regionInput == "(All)") {
      idx <- rep(TRUE, nrow(dat))
    } else {
      idx <- dat$region == input$regionInput
    }
    leaflet(dat) %>%
      addProviderTiles("Esri.WorldImagery") %>%
      addCircleMarkers(color = "blue",
                       radius = 2, 
                       stroke = FALSE, 
                       fillOpacity = 0.5, 
                       lng = dat[idx, "x"], 
                       lat = dat[idx, "y"])
  })
})

# Run the application 
shinyApp(ui, server)
© www.soinside.com 2019 - 2024. All rights reserved.