Skip to content

Instantly share code, notes, and snippets.

@charliejhadley
Created June 29, 2021 14:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charliejhadley/3e5e9491224b40e8e9a0b2bc22594e1c to your computer and use it in GitHub Desktop.
Save charliejhadley/3e5e9491224b40e8e9a0b2bc22594e1c to your computer and use it in GitHub Desktop.
Demonstration of plotOutput("gg_map", click = "ggmap_click") functionality for geom_sf()
library("shiny")
library("tidyverse")
library("rnaturalearthdata")
library("sf")
# Using Africa instead of whole world as countries110 contains
# 3 invalid geometries. Also, too many examples use the USA everytime
africa_sf <- countries110 %>%
st_as_sf() %>%
st_transform(4326) %>%
filter(continent == "Africa")
ui <- fluidPage(
h1("Plot brush with geom_sf"),
wellPanel("Click in a country to populate the table below the chart"),
plotOutput(
"gg_world_map",
click = "gg_world_map_click",
height = "600px",
width = "100%"
),
wellPanel("The table below provides detail on the selected country"),
tableOutput("table_click")
)
server <- function(input, output, session) {
output$gg_world_map <- renderPlot({
ggplot() +
geom_sf(data = africa_sf)
}, res = 96)
output$table_click <- renderTable({
if (is.null(input$gg_world_map_click)) {
return()
}
selected_point <- tibble(long = input$gg_world_map_click$x,
lat = input$gg_world_map_click$y) %>%
st_as_sf(coords = c("long", "lat"),
crs = 4326)
st_intersection(selected_point, countries_sf) %>%
st_drop_geometry() %>%
select(name, pop_est, gdp_md_est)
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment