|
library(shiny) |
|
library(leaflet) |
|
library(plotly) |
|
library(rgdal) |
|
# devtools::install_github("ropensci/geojsonio") |
|
library(geojsonio) |
|
# devtools::install_github("ateucher/rmapshaper") |
|
library(rmapshaper) |
|
|
|
#tarr <- readOGR(dsn = '.', layer = 'tarrant_precincts') |
|
#tarr_simp <- ms_simplify(tarr) |
|
#tarrxy <- spTransform(tarr_simp, CRS("+proj=longlat +datum=WGS84")) |
|
#tarrxy <- tarrxy[tarrxy$pctrep != -1 & tarrxy$pctwhite != -1, ] |
|
#l1 <- length(tarrxy) - 1 |
|
#tarrxy$id <- 0:l1 |
|
#geojson_write(tarrxy, file = 'tarrxy.geojson') |
|
|
|
if (!file.exists('tarrxy.geojson')) { |
|
download.file( |
|
'https://gist.githubusercontent.com/walkerke/da941dac84f730adcdde/raw/c65cd4886c10df032c0d3fdf1e430d583fa8c15a/tarrxy.geojson', |
|
'tarrxy.geojson' |
|
) |
|
} |
|
tarrxy <- geojson_read('tarrxy.geojson', what = 'sp') |
|
|
|
ui <- fluidPage( |
|
|
|
titlePanel("Linked brushing with Plotly and Leaflet in Shiny"), |
|
|
|
fixedRow( |
|
column(width = 6, |
|
plotlyOutput('scatter')) |
|
), |
|
|
|
fixedRow( |
|
column(width = 6, |
|
leafletOutput('map')) |
|
) |
|
|
|
) |
|
|
|
|
|
server <- function(input, output, session) { |
|
|
|
output$scatter <- renderPlotly({ |
|
|
|
g <- ggplot(tarrxy@data, aes(x = pctwhite, y = pctrep)) + |
|
geom_point() + |
|
xlab('Percent non-Hispanic white, 2010') + |
|
ylab('Percent voting Republican, 2012') |
|
|
|
ggplotly(g, source = 'source') %>% layout(dragmode = 'lasso') |
|
|
|
}) |
|
|
|
selected_precincts <- reactive({ |
|
|
|
eventdata <- event_data('plotly_selected', source = 'source') |
|
|
|
precincts <- as.numeric(eventdata[['pointNumber']]) |
|
|
|
sub <- tarrxy[tarrxy$id %in% precincts, ] |
|
|
|
return(sub) |
|
|
|
}) |
|
|
|
output$map <- renderLeaflet({ |
|
|
|
tarrant_map <- leaflet() %>% |
|
addProviderTiles('CartoDB.DarkMatter') %>% |
|
addPolygons(data = tarrxy, weight = 1, smoothFactor = 0.2, |
|
color = 'white', fillColor = 'grey') %>% |
|
addPolygons(data = selected_precincts(), fill = FALSE, color = '#FFFF00', |
|
opacity = 1) |
|
|
|
tarrant_map |
|
|
|
}) |
|
} |
|
|
|
shinyApp(ui = ui, server = server) |
Very cool stuff! Thanks for sharing. You have this setup to update leaflet based upon some ggplot brushing...what about updating ggplot based upon leaflet brushing?