diego-ellis-soto commited on
Commit
aedb415
Β·
1 Parent(s): 8c6f808

Readme update

Browse files
R/.DS_Store CHANGED
Binary files a/R/.DS_Store and b/R/.DS_Store differ
 
R/rsconnect/.DS_Store DELETED
Binary file (6.15 kB)
 
README.md CHANGED
@@ -1,5 +1,11 @@
1
  # SF_biodiv_access_shiny
2
 
 
 
 
 
 
 
3
  # Next steps: Optimize preanno of sf gbif and cbg
4
 
5
  # Public transport ddata
 
1
  # SF_biodiv_access_shiny
2
 
3
+ The aim of this Shiny app is to provide decision support for the Reimagining San Francisco Initiative
4
+
5
+ This Shiny App takes the input in the form of a user clicker on a map and selecting the transportation mode and calculates a isochrome.
6
+ The background then allows to identify biodiversity around a calculted isochrome as well as socio-economic and environmental variables
7
+ It further calculates a summary table of the GBIF data located within the isochrome
8
+
9
  # Next steps: Optimize preanno of sf gbif and cbg
10
 
11
  # Public transport ddata
app.R ADDED
@@ -0,0 +1,1081 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Get working directory, perhaps shiny apps is not receiving the data and the www?
2
+ # rsconnect::setAccountInfo(name='diego-ellis-soto', token='A47BE3C9E4B9EBCDFEC889AF31F64154', secret='g2Q2rxeYCiwlH81EkPXcCGsiHMgdyhTznJRmHtea')
3
+ # deployApp()
4
+ # Add that you can hover over the greespace and get its name
5
+ # Improve the titles of the ggplots of the model coefficient estimates and of ggplot using the gbif summary table on data avialability vs species richness. Also log transform these values for better data visualization
6
+ # Also the ggplot of data avialability vs species richness. should also update if the user decides to subset by class or family. Until then, its okay to retain the general plot using all the data from gbif_sf
7
+
8
+ # Optimize some calculations? Shorten
9
+
10
+
11
+
12
+
13
+
14
+ ###############################################################################
15
+ # Shiny App: San Francisco Biodiversity Access Decision Support Tool
16
+ # Author: Diego Ellis Soto, et al.
17
+ # University of California Berkeley, ESPM
18
+ # California Academy of Sciences
19
+ ###############################################################################
20
+
21
+ library(shiny)
22
+ library(leaflet)
23
+ library(mapboxapi)
24
+ library(tidyverse)
25
+ library(tidycensus)
26
+ library(sf)
27
+ library(DT)
28
+ library(RColorBrewer)
29
+ library(terra)
30
+ library(data.table) # for fread
31
+ library(mapview) # for mapview objects
32
+ library(sjPlot) # for plotting lm model coefficients
33
+ library(sjlabelled) # optional if needed for sjPlot
34
+
35
+ # ------------------------------------------------
36
+ # 1) API Keys
37
+ # ------------------------------------------------
38
+ mapbox_token <- "pk.eyJ1Ijoia3dhbGtlcnRjdSIsImEiOiJjbHc3NmI0cDMxYzhyMmt0OXBiYnltMjVtIn0.Thtu6WqIhOfin6AykskM2g"
39
+ mb_access_token(mapbox_token, install = FALSE)
40
+
41
+ # ------------------------------------------------
42
+ # 2) Load Data
43
+ # ------------------------------------------------
44
+ # -- Greenspace
45
+ getwd()
46
+ osm_greenspace <- st_read("data/greenspaces_osm_nad83.shp", quiet = TRUE) %>%
47
+ st_transform(4326)
48
+ if (!"name" %in% names(osm_greenspace)) {
49
+ osm_greenspace$name <- "Unnamed Greenspace"
50
+ }
51
+
52
+ # -- NDVI Raster
53
+ ndvi <- rast("data/SF_EastBay_NDVI_Sentinel_10.tif")
54
+
55
+ # -- GBIF data
56
+ # Load what is basically inter_gbif !!!!!
57
+ # load("data/sf_gbif.Rdata") # => sf_gbif
58
+ load('data/gbif_census_ndvi_anno.Rdata')
59
+ vect_gbif <- vect(sf_gbif)
60
+ # -- Precomputed CBG data
61
+ load('data/cbg_vect_sf.Rdata')
62
+ if (!"unique_species" %in% names(cbg_vect_sf)) {
63
+ cbg_vect_sf$unique_species <- cbg_vect_sf$n_species
64
+ }
65
+ if (!"n_observations" %in% names(cbg_vect_sf)) {
66
+ cbg_vect_sf$n_observations <- cbg_vect_sf$n
67
+ }
68
+ if (!"median_inc" %in% names(cbg_vect_sf)) {
69
+ cbg_vect_sf$median_inc <- cbg_vect_sf$medincE
70
+ }
71
+ if (!"ndvi_mean" %in% names(cbg_vect_sf)) {
72
+ cbg_vect_sf$ndvi_mean <- cbg_vect_sf$ndvi_sentinel
73
+ }
74
+
75
+ # -- Hotspots/Coldspots
76
+ biodiv_hotspots <- st_read("data/hotspots.shp", quiet = TRUE) %>% st_transform(4326)
77
+ biodiv_coldspots <- st_read("data/coldspots.shp", quiet = TRUE) %>% st_transform(4326)
78
+
79
+ # ------------------------------------------------
80
+ # 3) UI
81
+ # ------------------------------------------------
82
+ ui <- fluidPage(
83
+ titlePanel("San Francisco Biodiversity Access Decision Support Tool"),
84
+
85
+ fluidRow(
86
+ column(
87
+ width = 12, align = "center",
88
+ tags$img(src = "UC Berkeley_logo.png",
89
+ height = "120px", style = "margin:10px;"),
90
+ tags$img(src = "California_academy_logo.png",
91
+ height = "120px", style = "margin:10px;"),
92
+ tags$img(src = "Reimagining_San_Francisco.png",
93
+ height = "120px", style = "margin:10px;")
94
+ )
95
+ ),
96
+
97
+ fluidRow(
98
+ column(
99
+ width = 12,
100
+ br(),
101
+ p("This application demonstrates an approach for exploring biodiversity access in San Francisco..."),
102
+ # (Your summary text can go here)
103
+ )
104
+ ),
105
+ br(),
106
+ fluidRow(
107
+ column(
108
+ width = 12,
109
+ br(),
110
+ tags$b("App Summary (Fill out with RSF data working group):"),
111
+ # Increasingly, we ask ourselves about what increasing access to biodiversity really means.
112
+ # Importantly, accessibility differs from human mobility in urban planning studies for equitable transportation systems.
113
+ p("
114
+ This application allows users to either click on a map or geocode an address (in progress)
115
+ to generate travel-time isochrones across multiple transportation modes (e.g., pedestrian, cycling, driving, driving during traffic).
116
+ It retrieves socio-economic data from precomputed Census variables, calculates NDVI,
117
+ and summarizes biodiversity records from GBIF. We explore what biodiversity access means
118
+ Users can explore information that we often relate to biodiversity in urban environments including greenspace coverage, population estimates, and species diversity within each isochrone."),
119
+
120
+ tags$b("Created by:"),
121
+ p(strong("Diego Ellis Soto", "Carl Boettiger, Rebecca Johnson, Christopher J. Schell")),
122
+
123
+ p("Contact Information",
124
+ strong("[email protected]"))
125
+
126
+ )
127
+ ),
128
+ br(),
129
+
130
+ tabsetPanel(
131
+
132
+ # 1) Isochrone Explorer
133
+ tabPanel("Isochrone Explorer",
134
+ sidebarLayout(
135
+ sidebarPanel(
136
+ radioButtons(
137
+ "location_choice",
138
+ "Select how to choose your location:",
139
+ choices = c("Address (Geocode)" = "address",
140
+ "Click on Map" = "map_click"),
141
+ selected = "map_click"
142
+ ),
143
+
144
+ conditionalPanel(
145
+ condition = "input.location_choice == 'address'",
146
+ textInput(
147
+ "user_address",
148
+ "Enter Address:",
149
+ value = "",
150
+ placeholder = "e.g., 1600 Amphitheatre Parkway, Mountain View, CA"
151
+ )
152
+ ),
153
+
154
+ checkboxGroupInput(
155
+ "transport_modes",
156
+ "Select Transportation Modes:",
157
+ choices = list("Driving" = "driving",
158
+ "Walking" = "walking",
159
+ "Cycling" = "cycling",
160
+ "Driving with Traffic"= "driving-traffic"),
161
+ selected = c("driving", "walking")
162
+ ),
163
+
164
+ checkboxGroupInput(
165
+ "iso_times",
166
+ "Select Isochrone Times (minutes):",
167
+ choices = list("5" = 5, "10" = 10, "15" = 15),
168
+ selected = c(5, 10)
169
+ ),
170
+
171
+ actionButton("generate_iso", "Generate Isochrones"),
172
+ actionButton("clear_map", "Clear")
173
+
174
+ ),
175
+
176
+ mainPanel(
177
+ leafletOutput("isoMap", height = 600),
178
+
179
+ fluidRow(
180
+ column(12,
181
+ br(),
182
+ uiOutput("bioScoreBox"),
183
+ uiOutput("closestGreenspaceUI")
184
+ )
185
+ ),
186
+
187
+ br(),
188
+ DTOutput("dataTable"),
189
+
190
+ br(),
191
+ fluidRow(
192
+ column(12,
193
+ plotOutput("bioSocPlot", height = "400px")
194
+ )
195
+ ),
196
+
197
+ br(),
198
+ fluidRow(
199
+ column(12,
200
+ plotOutput("collectionPlot", height = "300px")
201
+ )
202
+ )
203
+ )
204
+ )
205
+ ),
206
+
207
+ #br.?
208
+ tabPanel(
209
+ "GBIF Summaries",
210
+ sidebarLayout(
211
+ sidebarPanel(
212
+ selectInput(
213
+ "class_filter",
214
+ "Select a GBIF Class to Summarize:",
215
+ choices = c("All", sort(unique(sf_gbif$class))),
216
+ selected = "All"
217
+ ),
218
+ selectInput(
219
+ "family_filter",
220
+ "Filter by Family (optional):",
221
+ choices = c("All", sort(unique(sf_gbif$family))),
222
+ selected = "All"
223
+ )
224
+ ),
225
+ mainPanel(
226
+ DTOutput("classTable"),
227
+ br(),
228
+ h3("Observations vs. Species Richness"),
229
+ plotOutput("obsVsSpeciesPlot", height = "400px"),
230
+ p("This plot displays the relationship between the number of observations and the species richness. Use this visualization to understand data coverage and biodiversity trends.")
231
+ )
232
+ )
233
+ ),
234
+ fluidRow(
235
+ column(
236
+ width = 12,
237
+ tags$b("Reimagining San Francisco (Fill out with CAS):"),
238
+ p("Reimagining San Francisco is an initiative aimed at integrating ecological, social,
239
+ and technological dimensions to shape a sustainable future for the Bay Area.
240
+ This collaboration unites diverse stakeholders to explore innovations in urban planning,
241
+ conservation, and community engagement. The Reimagining San Francisco Data Working Group has been tasked with identifying and integrating multiple sources of socio-ecological biodiversity information in a co-development framework."),
242
+
243
+ tags$b("Why Biodiversity Access Matters (Polish this):"),
244
+ p("Ensuring equitable access to biodiversity is essential for human well-being,
245
+ ecological resilience, and global policy decisions related to conservation.
246
+ Areas with higher biodiversity can support ecosystem services including pollinators, moderate climate extremes,
247
+ and provide cultural, recreational, and health benefits to local communities.
248
+ Recognizing that cities are particularly complex socio-ecological systems facing both legacies of sociocultural practices as well as current ongoing dynamic human activities and pressures.
249
+ Incorporating multiple facets of biodiversity metrics alongside variables employed by city planners, human geographers, and decision-makers into urban planning will allow a more integrative lens in creating a sustainable future for cities and their residents."),
250
+
251
+ tags$b("How We Calculate Biodiversity Access Percentile:"),
252
+ p("Total unique species found within the user-generated isochrone.
253
+ We then compare that value to the distribution of unique species counts across all census block groups,
254
+ converting that comparison into a percentile ranking (Polish this, look at the 15 Minute city).
255
+ A higher percentile indicates greater biodiversity within the chosen area,
256
+ relative to other parts of the city or region.")
257
+ ),
258
+
259
+ tags$b("Next Steps:"),
260
+ tags$ul(
261
+ tags$li("Add impervious surface"),
262
+ tags$li("National walkability score"),
263
+ tags$li("Social vulnerability score"),
264
+ tags$li("NatureServe biodiversity maps"),
265
+ tags$li("Calculate cold-hotspots within ggregation of H6 bins instead of by census block group: Ask Carl"),
266
+ tags$li("Species range maps"),
267
+ tags$li("Add common name GBIF"),
268
+ tags$li("Partner orgs"),
269
+ tags$li("Optimize speed -> store variables -> H-ify the world?"),
270
+ tags$li("Brainstorm and co-develop the biodiversity access score"),
271
+ tags$li("For the GBIF summaries, add an annotated GBIF_sf with environmental variables so we can see landcover type association across the biodiversity within the isochrone.")
272
+ )
273
+ )
274
+
275
+
276
+
277
+ # )
278
+
279
+ # Separate section for the plot outside of the "GBIF Summaries" tab
280
+
281
+ # tabsetPanel(
282
+
283
+ # # 1) Isochrone Explorer
284
+ # tabPanel(
285
+ # mainPanel(
286
+ # DTOutput("classTable"),
287
+ # br(),
288
+ # fluidRow(
289
+ # column(
290
+ # 6,
291
+ # # A simple scatter or line plot for n_observations vs n_species
292
+ # plotOutput("obsVsSpeciesPlot", height = "300px")
293
+ # )
294
+ # # ,
295
+ # # column(
296
+ # # 6,
297
+ # # # A regression model plot using sjPlot
298
+ # # plotOutput("lmCoefficientsPlot", height = "300px")
299
+ # # )
300
+ # )
301
+ # )
302
+ # )
303
+ # ),
304
+ #
305
+ # br()
306
+
307
+ )
308
+
309
+
310
+ # fluidRow(
311
+ # column(
312
+ # 12,
313
+ # tags$h3("Species Richness vs Data Availability"),
314
+ # fluidRow(
315
+ # column(6, uiOutput("mapNUI")),
316
+ # column(6, uiOutput("mapSpeciesUI"))
317
+ # )
318
+ # )
319
+ # )
320
+ )
321
+
322
+ # ------------------------------------------------
323
+ # 4) Server
324
+ # ------------------------------------------------
325
+ server <- function(input, output, session) {
326
+
327
+ chosen_point <- reactiveVal(NULL)
328
+
329
+ # ------------------------------------------------
330
+ # Leaflet Base + Hide Overlays
331
+ # ------------------------------------------------
332
+ output$isoMap <- renderLeaflet({
333
+ pal_cbg <- colorNumeric("YlOrRd", cbg_vect_sf$medincE)
334
+
335
+ pal_rich <- colorNumeric("YlOrRd", domain = cbg_vect_sf$unique_species)
336
+ # 2) Color palette for data availability
337
+ pal_data <- colorNumeric("Blues", domain = cbg_vect_sf$n_observations)
338
+
339
+
340
+ leaflet() %>%
341
+ addTiles(group = "Street Map (Default)") %>%
342
+ addProviderTiles(providers$Esri.WorldImagery, group = "Satellite (ESRI)") %>%
343
+ addProviderTiles(providers$CartoDB.Positron, group = "CartoDB.Positron") %>%
344
+
345
+ addPolygons(
346
+ data = cbg_vect_sf,
347
+ group = "Income",
348
+ # fillColor = ~pal_cbg(unique_species),
349
+ fillColor = ~pal_cbg(medincE),
350
+ fillOpacity = 0.6,
351
+ color = "white",
352
+ weight = 1,
353
+ # label = "Income",
354
+ label=~GEOID,
355
+ highlightOptions = highlightOptions(
356
+ weight = 5,
357
+ color = "blue",
358
+ fillOpacity = 0.5,
359
+ bringToFront = TRUE
360
+ ),
361
+ labelOptions = labelOptions(
362
+ style = list("font-weight" = "bold", "color" = "blue"),
363
+ textsize = "12px",
364
+ direction = "auto"
365
+ )
366
+ ) %>%
367
+
368
+ addPolygons(
369
+ data = osm_greenspace,
370
+ group = "Greenspace",
371
+ fillColor = "darkgreen",
372
+ fillOpacity = 0.3,
373
+ color = "green",
374
+ weight = 1,
375
+ label = ~name,
376
+ highlightOptions = highlightOptions(
377
+ weight = 5,
378
+ color = "blue",
379
+ fillOpacity = 0.5,
380
+ bringToFront = TRUE
381
+ ),
382
+ labelOptions = labelOptions(
383
+ style = list("font-weight" = "bold", "color" = "blue"),
384
+ textsize = "12px",
385
+ direction = "auto"
386
+ )
387
+ ) %>%
388
+
389
+ addPolygons(
390
+ data = biodiv_hotspots,
391
+ group = "Hotspots (KnowBR)",
392
+ fillColor = "firebrick",
393
+ fillOpacity = 0.2,
394
+ color = "firebrick",
395
+ weight = 2,
396
+ label = ~GEOID,
397
+ highlightOptions = highlightOptions(
398
+ weight = 5,
399
+ color = "blue",
400
+ fillOpacity = 0.5,
401
+ bringToFront = TRUE
402
+ ),
403
+ labelOptions = labelOptions(
404
+ style = list("font-weight" = "bold", "color" = "blue"),
405
+ textsize = "12px",
406
+ direction = "auto"
407
+ )
408
+ ) %>%
409
+
410
+ addPolygons(
411
+ data = biodiv_coldspots,
412
+ group = "Coldspots (KnowBR)",
413
+ fillColor = "navyblue",
414
+ fillOpacity = 0.2,
415
+ color = "navyblue",
416
+ weight = 2,
417
+ label = ~GEOID,
418
+ highlightOptions = highlightOptions(
419
+ weight = 5,
420
+ color = "blue",
421
+ fillOpacity = 0.5,
422
+ bringToFront = TRUE
423
+ ),
424
+ labelOptions = labelOptions(
425
+ style = list("font-weight" = "bold", "color" = "blue"),
426
+ textsize = "12px",
427
+ direction = "auto"
428
+ )
429
+ ) %>%
430
+
431
+ # Add richness and nobs
432
+ # -- Richness layer
433
+ addPolygons(
434
+ data = cbg_vect_sf,
435
+ group = "Species Richness",
436
+ fillColor = ~pal_rich(unique_species),
437
+ fillOpacity = 0.6,
438
+ color = "white",
439
+ weight = 1,
440
+ label =~unique_species,
441
+ popup = ~paste0(
442
+ "<strong>GEOID: </strong>", GEOID,
443
+ "<br><strong>Species Richness: </strong>", unique_species,
444
+ "<br><strong>Observations: </strong>", n_observations,
445
+ "<br><strong>Median Income: </strong>", median_inc,
446
+ "<br><strong>Mean NDVI: </strong>", ndvi_mean
447
+ )
448
+ ) %>%
449
+
450
+ # -- Data Availability layer
451
+ addPolygons(
452
+ data = cbg_vect_sf,
453
+ group = "Data Availability",
454
+ fillColor = ~pal_data(n_observations),
455
+ fillOpacity = 0.6,
456
+ color = "white",
457
+ weight = 1,
458
+ label =~n_observations,
459
+ popup = ~paste0(
460
+ "<strong>GEOID: </strong>", GEOID,
461
+ "<br><strong>Observations: </strong>", n_observations,
462
+ "<br><strong>Species Richness: </strong>", unique_species,
463
+ "<br><strong>Median Income: </strong>", median_inc,
464
+ "<br><strong>Mean NDVI: </strong>", ndvi_mean
465
+ )
466
+ ) %>%
467
+
468
+
469
+ setView(lng = -122.4194, lat = 37.7749, zoom = 12) %>%
470
+ addLayersControl(
471
+ baseGroups = c("Street Map (Default)", "Satellite (ESRI)", "CartoDB.Positron"),
472
+ overlayGroups = c("Income", "Greenspace","Species Richness", "Data Availability",
473
+ "Hotspots (KnowBR)", "Coldspots (KnowBR)"),
474
+ options = layersControlOptions(collapsed = FALSE)
475
+ ) %>%
476
+ hideGroup("Income") %>%
477
+ hideGroup("Greenspace") %>%
478
+ hideGroup("Hotspots (KnowBR)") %>%
479
+ hideGroup("Coldspots (KnowBR)") %>%
480
+ hideGroup("Species Richness") %>%
481
+ hideGroup("Data Availability")
482
+ })
483
+
484
+
485
+ # ------------------------------------------------
486
+ # Observe map clicks (location_choice = 'map_click')
487
+ # ------------------------------------------------
488
+ observeEvent(input$isoMap_click, {
489
+ req(input$location_choice == "map_click")
490
+ click <- input$isoMap_click
491
+ if (!is.null(click)) {
492
+ chosen_point(c(lon = click$lng, lat = click$lat))
493
+ leafletProxy("isoMap") %>%
494
+ clearMarkers() %>%
495
+ addCircleMarkers(
496
+ lng = click$lng, lat = click$lat,
497
+ radius = 6, color = "firebrick",
498
+ label = "Map Click Location"
499
+ )
500
+ }
501
+ })
502
+
503
+ # ------------------------------------------------
504
+ # Observe clearinf of map
505
+ # ------------------------------------------------
506
+ observeEvent(input$clear_map, {
507
+ # Reset the chosen point
508
+ chosen_point(NULL)
509
+
510
+ # Clear all markers and isochrones from the map
511
+ leafletProxy("isoMap") %>%
512
+ clearMarkers() %>%
513
+ clearShapes() %>%
514
+ clearGroup("Isochrones") %>%
515
+ clearGroup("NDVI Raster")
516
+
517
+ # Optional: Reset any other reactive values if needed
518
+ showNotification("Map cleared. You can select a new location.")
519
+ })
520
+
521
+ # ------------------------------------------------
522
+ # Generate Isochrones
523
+ # ------------------------------------------------
524
+ isochrones_data <- eventReactive(input$generate_iso, {
525
+
526
+ leafletProxy("isoMap") %>%
527
+ clearGroup("Isochrones") %>%
528
+ clearGroup("NDVI Raster")
529
+
530
+ # If user selected address:
531
+ if (input$location_choice == "address") {
532
+ if (nchar(input$user_address) < 5) {
533
+ showNotification("Please enter a more complete address.", type = "error")
534
+ return(NULL)
535
+ }
536
+
537
+ loc_df <- tryCatch({
538
+ mb_geocode(input$user_address, access_token = mapbox_token)
539
+ }, error = function(e) {
540
+ showNotification(paste("Geocoding failed:", e$message), type = "error")
541
+ NULL
542
+ })
543
+
544
+ # Check for valid lat/lon
545
+ if (is.null(loc_df) || nrow(loc_df) == 0 || is.na(loc_df$lon[1]) || is.na(loc_df$lat[1])) {
546
+ showNotification("No valid geocoding results found.", type = "warning")
547
+ return(NULL)
548
+ }
549
+
550
+ chosen_point(c(lon = loc_df$lon[1], lat = loc_df$lat[1]))
551
+
552
+ leafletProxy("isoMap") %>%
553
+ clearMarkers() %>%
554
+ addCircleMarkers(
555
+ lng = loc_df$lon[1], lat = loc_df$lat[1],
556
+ radius = 6, color = "navyblue",
557
+ label = "Geocoded Address"
558
+ ) %>%
559
+ setView(lng = loc_df$lon[1], lat = loc_df$lat[1], zoom = 13)
560
+ }
561
+
562
+ pt <- chosen_point()
563
+ if (is.null(pt)) {
564
+ showNotification("No location selected! Provide an address or click the map.", type = "error")
565
+ return(NULL)
566
+ }
567
+ if (length(input$transport_modes) == 0) {
568
+ showNotification("Select at least one transportation mode.", type = "error")
569
+ return(NULL)
570
+ }
571
+ if (length(input$iso_times) == 0) {
572
+ showNotification("Select at least one isochrone time.", type = "error")
573
+ return(NULL)
574
+ }
575
+
576
+ location_sf <- st_as_sf(
577
+ data.frame(lon = pt["lon"], lat = pt["lat"]),
578
+ coords = c("lon","lat"), crs = 4326
579
+ )
580
+
581
+ iso_list <- list()
582
+ for (mode in input$transport_modes) {
583
+ for (t in input$iso_times) {
584
+ iso <- tryCatch({
585
+ mb_isochrone(location_sf, time = as.numeric(t), profile = mode,
586
+ access_token = mapbox_token)
587
+ }, error = function(e) {
588
+ showNotification(paste("Isochrone error:", mode, t, e$message), type = "error")
589
+ NULL
590
+ })
591
+ if (!is.null(iso)) {
592
+ iso$mode <- mode
593
+ iso$time <- t
594
+ iso_list <- append(iso_list, list(iso))
595
+ }
596
+ }
597
+ }
598
+ if (length(iso_list) == 0) {
599
+ showNotification("No isochrones generated.", type = "warning")
600
+ return(NULL)
601
+ }
602
+
603
+ all_iso <- do.call(rbind, iso_list) %>% st_transform(4326)
604
+ all_iso
605
+ })
606
+
607
+ # ------------------------------------------------
608
+ # Plot Isochrones + NDVI
609
+ # ------------------------------------------------
610
+ observeEvent(isochrones_data(), {
611
+ iso_data <- isochrones_data()
612
+ req(iso_data)
613
+
614
+ iso_data$iso_group <- paste(iso_data$mode, iso_data$time, sep = "_")
615
+ pal <- colorRampPalette(brewer.pal(8, "Set2"))
616
+ cols <- pal(nrow(iso_data))
617
+
618
+ for (i in seq_len(nrow(iso_data))) {
619
+ poly_i <- iso_data[i, ]
620
+ leafletProxy("isoMap") %>%
621
+ addPolygons(
622
+ data = poly_i,
623
+ group = "Isochrones",
624
+ color = cols[i],
625
+ weight = 2,
626
+ fillOpacity = 0.4,
627
+ label = paste0(poly_i$mode, " - ", poly_i$time, " mins")
628
+ )
629
+ }
630
+
631
+ iso_union <- st_union(iso_data)
632
+ iso_union_vect <- vect(iso_union)
633
+ ndvi_crop <- crop(ndvi, iso_union_vect)
634
+ ndvi_mask <- mask(ndvi_crop, iso_union_vect)
635
+ ndvi_vals <- values(ndvi_mask)
636
+ ndvi_vals <- ndvi_vals[!is.na(ndvi_vals)]
637
+
638
+ # Could be removed ####
639
+ if (length(ndvi_vals) > 0) {
640
+ ndvi_pal <- colorNumeric("YlGn", domain = range(ndvi_vals, na.rm = TRUE), na.color = "transparent")
641
+
642
+ leafletProxy("isoMap") %>%
643
+ addRasterImage(
644
+ x = ndvi_mask,
645
+ colors = ndvi_pal,
646
+ opacity = 0.7,
647
+ project = TRUE,
648
+ group = "NDVI Raster"
649
+ ) %>%
650
+ addLegend(
651
+ position = "bottomright",
652
+ pal = ndvi_pal,
653
+ values = ndvi_vals,
654
+ title = "NDVI"
655
+ )
656
+ }
657
+
658
+ leafletProxy("isoMap") %>%
659
+ addLayersControl(
660
+ baseGroups = c("Street Map (Default)", "Satellite (ESRI)", "CartoDB.Positron"),
661
+ overlayGroups = c("Income", "Greenspace",
662
+ "Hotspots (KnowBR)", "Coldspots (KnowBR)",
663
+ "Isochrones", "NDVI Raster"),
664
+ options = layersControlOptions(collapsed = FALSE)
665
+ )
666
+ })
667
+
668
+ # ------------------------------------------------
669
+ # socio_data Reactive + Summaries
670
+ # ------------------------------------------------
671
+ socio_data <- reactive({
672
+ iso_data <- isochrones_data()
673
+ if (is.null(iso_data) || nrow(iso_data) == 0) {
674
+ return(data.frame())
675
+ }
676
+
677
+ acs_wide <- cbg_vect_sf %>%
678
+ mutate(
679
+ population = popE,
680
+ med_income = medincE
681
+ )
682
+
683
+ hotspot_union <- st_union(biodiv_hotspots)
684
+ coldspot_union <- st_union(biodiv_coldspots)
685
+
686
+ results <- data.frame()
687
+
688
+ # Calculate distance to coldspot and hotspots
689
+ for (i in seq_len(nrow(iso_data))) {
690
+ poly_i <- iso_data[i, ]
691
+
692
+ dist_hot <- st_distance(poly_i, hotspot_union)
693
+ dist_cold <- st_distance(poly_i, coldspot_union)
694
+ dist_hot_km <- round(as.numeric(min(dist_hot)) / 1000, 3)
695
+ dist_cold_km <- round(as.numeric(min(dist_cold)) / 1000, 3)
696
+
697
+ inter_acs <- st_intersection(acs_wide, poly_i)
698
+ #
699
+ vect_acs_wide <- vect(acs_wide)
700
+ vect_poly_i <- vect(poly_i)
701
+ inter_acs <- intersect(vect_acs_wide, vect_poly_i)
702
+ inter_acs = st_as_sf(inter_acs)
703
+ #
704
+
705
+ pop_total <- 0
706
+ inc_str <- "N/A"
707
+ if (nrow(inter_acs) > 0) {
708
+ inter_acs$area <- st_area(inter_acs)
709
+ inter_acs$area_num <- as.numeric(inter_acs$area)
710
+ inter_acs$area_ratio <- inter_acs$area_num / as.numeric(st_area(inter_acs))
711
+ inter_acs$weighted_pop <- inter_acs$population * inter_acs$area_ratio
712
+
713
+ pop_total <- round(sum(inter_acs$weighted_pop, na.rm = TRUE))
714
+
715
+ w_income <- sum(inter_acs$med_income * inter_acs$area_num, na.rm = TRUE) /
716
+ sum(inter_acs$area_num, na.rm = TRUE)
717
+ if (!is.na(w_income) && w_income > 0) {
718
+ inc_str <- paste0("$", formatC(round(w_income, 2), format = "f", big.mark = ","))
719
+ }
720
+ }
721
+
722
+ # inter_gs <- st_intersection(osm_greenspace, poly_i)
723
+
724
+ vec_osm_greenspace = vect(osm_greenspace)
725
+ vect_poly_i <- vect(poly_i)
726
+ inter_gs <- intersect(vec_osm_greenspace, vect_poly_i)
727
+ inter_gs = st_as_sf(inter_gs)
728
+
729
+
730
+
731
+ gs_area_m2 <- 0
732
+ if (nrow(inter_gs) > 0) {
733
+ gs_area_m2 <- sum(st_area(inter_gs))
734
+ }
735
+ iso_area_m2 <- as.numeric(st_area(poly_i))
736
+ gs_area_m2 <- as.numeric(gs_area_m2)
737
+ gs_percent <- ifelse(iso_area_m2 > 0, 100 * gs_area_m2 / iso_area_m2, 0)
738
+
739
+ poly_vect <- vect(poly_i)
740
+ ndvi_crop <- crop(ndvi, poly_vect)
741
+ ndvi_mask <- mask(ndvi_crop, poly_vect)
742
+ ndvi_vals <- values(ndvi_mask)
743
+ ndvi_vals <- ndvi_vals[!is.na(ndvi_vals)]
744
+ mean_ndvi <- ifelse(length(ndvi_vals) > 0, round(mean(ndvi_vals, na.rm=TRUE), 3), NA)
745
+
746
+ # inter_gbif <- st_intersection(sf_gbif, poly_i)
747
+
748
+ vect_poly_i = vect(poly_i)
749
+
750
+ inter_gbif = intersect(vect_gbif,vect_poly_i)
751
+ inter_gbif = st_as_sf(inter_gbif)
752
+ # inter_gbif <- st_intersection(sf_gbif, poly_i)
753
+
754
+
755
+ inter_gbif_acs = sf_gbif |> dplyr::mutate(income = medincE,
756
+ ndvi = ndvi_sentinel)
757
+
758
+
759
+ n_records <- nrow(inter_gbif)
760
+ n_species <- length(unique(inter_gbif$species))
761
+
762
+ n_birds <- length(unique(inter_gbif$species[ inter_gbif$class == "Aves" ]))
763
+ n_mammals <- length(unique(inter_gbif$species[ inter_gbif$class == "Mammalia" ]))
764
+ n_plants <- length(unique(inter_gbif$species[ inter_gbif$class %in%
765
+ c("Magnoliopsida","Liliopsida","Pinopsida","Polypodiopsida",
766
+ "Equisetopsida","Bryopsida","Marchantiopsida") ]))
767
+
768
+ iso_area_km2 <- round(iso_area_m2 / 1e6, 3)
769
+ # iso_area_sqm <- round(iso_area_m2, 2)
770
+
771
+ row_i <- data.frame(
772
+ Mode = tools::toTitleCase(poly_i$mode),
773
+ Time = poly_i$time,
774
+ # IsochroneArea_m2 = iso_area_sqm,
775
+ IsochroneArea_km2 = iso_area_km2,
776
+ DistToHotspot_km = dist_hot_km,
777
+ DistToColdspot_km = dist_cold_km,
778
+ EstimatedPopulation = pop_total,
779
+ MedianIncome = inc_str,
780
+ MeanNDVI = ifelse(!is.na(mean_ndvi), mean_ndvi, "N/A"),
781
+ GBIF_Records = n_records,
782
+ GBIF_Species = n_species,
783
+ Bird_Species = n_birds,
784
+ Mammal_Species = n_mammals,
785
+ Plant_Species = n_plants,
786
+ Greenspace_m2 = round(gs_area_m2, 2),
787
+ Greenspace_percent = round(gs_percent, 2),
788
+ stringsAsFactors = FALSE
789
+ )
790
+ results <- rbind(results, row_i)
791
+ }
792
+
793
+ iso_union <- st_union(iso_data)
794
+
795
+ # inter_all_gbif <- st_intersection(sf_gbif, iso_union)
796
+
797
+ # vect_gbif <- vect(sf_gbif)
798
+ vect_iso <- vect(iso_union)
799
+ inter_all_gbif <- intersect(vect_gbif, vect_iso)
800
+ inter_all_gbif = st_as_sf(inter_all_gbif)
801
+
802
+
803
+ union_n_species <- length(unique(inter_all_gbif$species))
804
+ rank_percentile <- round(100 * ecdf(cbg_vect_sf$unique_species)(union_n_species), 1)
805
+ attr(results, "bio_percentile") <- rank_percentile
806
+
807
+ # Closest Greenspace from ANY part of the isochrone
808
+ dist_mat <- st_distance(iso_union, osm_greenspace) # 1 x N matrix
809
+ if (length(dist_mat) > 0) {
810
+ min_dist <- min(dist_mat)
811
+ min_idx <- which.min(dist_mat)
812
+ gs_name <- osm_greenspace$name[min_idx]
813
+ attr(results, "closest_greenspace") <- gs_name
814
+ } else {
815
+ attr(results, "closest_greenspace") <- "None"
816
+ }
817
+
818
+ results
819
+ })
820
+
821
+ # ------------------------------------------------
822
+ # Render main summary table
823
+ # ------------------------------------------------
824
+ output$dataTable <- renderDT({
825
+ df <- socio_data()
826
+ if (nrow(df) == 0) {
827
+ return(DT::datatable(data.frame("Message" = "No isochrones generated yet.")))
828
+ }
829
+ DT::datatable(
830
+ df,
831
+ colnames = c(
832
+ "Mode" = "Mode",
833
+ "Time (min)" = "Time",
834
+ # "Area (mΒ²)" = "IsochroneArea_m2",
835
+ "Area (kmΒ²)" = "IsochroneArea_km2",
836
+ "Dist. Hotspot (km)" = "DistToHotspot_km",
837
+ "Dist. Coldspot (km)" = "DistToColdspot_km",
838
+ "Population" = "EstimatedPopulation",
839
+ "Median Income" = "MedianIncome",
840
+ "Mean NDVI" = "MeanNDVI",
841
+ "GBIF Records" = "GBIF_Records",
842
+ "Unique Species" = "GBIF_Species",
843
+ "Bird Species" = "Bird_Species",
844
+ "Mammal Species" = "Mammal_Species",
845
+ "Plant Species" = "Plant_Species",
846
+ "Greenspace (mΒ²)" = "Greenspace_m2",
847
+ "Greenspace (%)" = "Greenspace_percent"
848
+ ),
849
+ options = list(pageLength = 10, autoWidth = TRUE),
850
+ rownames = FALSE
851
+ )
852
+ })
853
+
854
+ # ------------------------------------------------
855
+ # Biodiversity Access Score + Closest Greenspace
856
+ # ------------------------------------------------
857
+ output$bioScoreBox <- renderUI({
858
+ df <- socio_data()
859
+ if (nrow(df) == 0) return(NULL)
860
+
861
+ percentile <- attr(df, "bio_percentile")
862
+ if (is.null(percentile)) percentile <- "N/A"
863
+ else percentile <- paste0(percentile, "th Percentile")
864
+
865
+ wellPanel(
866
+ HTML(paste0("<h2>Biodiversity Access Score: ", percentile, "</h2>"))
867
+ )
868
+ })
869
+
870
+ output$closestGreenspaceUI <- renderUI({
871
+ df <- socio_data()
872
+ if (nrow(df) == 0) return(NULL)
873
+ gs_name <- attr(df, "closest_greenspace")
874
+ if (is.null(gs_name)) gs_name <- "None"
875
+
876
+ tagList(
877
+ strong("Closest Greenspace (from any part of the Isochrone):"),
878
+ p(gs_name)
879
+ )
880
+ })
881
+
882
+ # ------------------------------------------------
883
+ # Secondary table: user-selected CLASS & FAMILY
884
+ # ------------------------------------------------
885
+ output$classTable <- renderDT({
886
+ iso_data <- isochrones_data()
887
+ if (is.null(iso_data) || nrow(iso_data) == 0) {
888
+ return(DT::datatable(data.frame("Message" = "No isochrones generated yet.")))
889
+ }
890
+
891
+ iso_union <- st_union(iso_data)
892
+ # inter_gbif <- st_intersection(sf_gbif, iso_union)
893
+
894
+
895
+ vect_iso <- vect(iso_union)
896
+ inter_gbif <- intersect(vect_gbif, vect_iso)
897
+ inter_gbif = st_as_sf(inter_gbif)
898
+
899
+
900
+
901
+ # Add a quick ACS intersection for mean income & NDVI if needed
902
+ acs_wide <- cbg_vect_sf %>% mutate(
903
+ income = median_inc,
904
+ ndvi = ndvi_mean
905
+ )
906
+ # this can be skipped !
907
+ # inter_gbif_acs <- st_intersection(inter_gbif, acs_wide)
908
+
909
+ inter_gbif_acs = sf_gbif |> dplyr::mutate(income = medincE,
910
+ ndvi = ndvi_sentinel)#We can do this because we preannotated ndvi and us census information
911
+
912
+ if (input$class_filter != "All") {
913
+ inter_gbif_acs <- inter_gbif_acs[ inter_gbif_acs$class == input$class_filter, ]
914
+ }
915
+ if (input$family_filter != "All") {
916
+ inter_gbif_acs <- inter_gbif_acs[ inter_gbif_acs$family == input$family_filter, ]
917
+ }
918
+
919
+ if (nrow(inter_gbif_acs) == 0) {
920
+ return(DT::datatable(data.frame("Message" = "No records for that combination in the isochrone.")))
921
+ }
922
+
923
+ species_counts <- inter_gbif_acs %>%
924
+ st_drop_geometry() %>%
925
+ group_by(species) %>%
926
+ summarize(
927
+ n_records = n(),
928
+ mean_income = round(mean(income, na.rm=TRUE), 2),
929
+ mean_ndvi = round(mean(ndvi, na.rm=TRUE), 3),
930
+ .groups = "drop"
931
+ ) %>%
932
+ arrange(desc(n_records))
933
+
934
+ DT::datatable(
935
+ species_counts,
936
+ colnames = c("Species", "Number of Records", "Mean Income", "Mean NDVI"),
937
+ options = list(pageLength = 10),
938
+ rownames = FALSE
939
+ )
940
+ })
941
+
942
+ # ------------------------------------------------
943
+ # Ggplot: Biodiversity & Socioeconomic Summary
944
+ # ------------------------------------------------
945
+ output$bioSocPlot <- renderPlot({
946
+ df <- socio_data()
947
+ if (nrow(df) == 0) return(NULL)
948
+
949
+ df_plot <- df %>%
950
+ mutate(IsoLabel = paste0(Mode, "-", Time, "min"))
951
+
952
+ ggplot(df_plot, aes(x = IsoLabel)) +
953
+ geom_col(aes(y = GBIF_Species), fill = "steelblue", alpha = 0.7) +
954
+ geom_line(aes(y = EstimatedPopulation / 1000, group = 1), color = "red", size = 1) +
955
+ geom_point(aes(y = EstimatedPopulation / 1000), color = "red", size = 3) +
956
+ labs(
957
+ x = "Isochrone (Mode-Time)",
958
+ y = "Blue bars: Unique Species \n | Red line: Population (thousands)",
959
+ title = "Biodiversity & Socioeconomic Summary"
960
+ ) +
961
+ theme_minimal(base_size = 14) +
962
+ theme(
963
+ axis.text.x = element_text(angle = 45, hjust = 1, size = 12),
964
+ axis.text.y = element_text(size = 12),
965
+ axis.title.x = element_text(size = 14),
966
+ axis.title.y = element_text(size = 14)
967
+ )
968
+ })
969
+
970
+ # ------------------------------------------------
971
+ # Bar plot: GBIF records by institutionCode
972
+ # ------------------------------------------------
973
+ output$collectionPlot <- renderPlot({
974
+ iso_data <- isochrones_data()
975
+ if (is.null(iso_data) || nrow(iso_data) == 0) {
976
+ plot.new()
977
+ title("No GBIF records found in this isochrone.")
978
+ return(NULL)
979
+ }
980
+
981
+ iso_union <- st_union(iso_data)
982
+ # inter_gbif <- st_intersection(sf_gbif, iso_union)
983
+
984
+ vect_iso <- vect(iso_union)
985
+ inter_gbif <- intersect(vect_gbif, vect_iso)
986
+ inter_gbif = st_as_sf(inter_gbif)
987
+
988
+
989
+
990
+ if (nrow(inter_gbif) == 0) {
991
+ plot.new()
992
+ title("No GBIF records found in this isochrone.")
993
+ return(NULL)
994
+ }
995
+
996
+ df_code <- inter_gbif %>%
997
+ st_drop_geometry() %>%
998
+ group_by(institutionCode) %>%
999
+ summarize(count = n(), .groups = "drop") %>%
1000
+ arrange(desc(count))
1001
+
1002
+ ggplot(df_code, aes(x = reorder(institutionCode, -count), y = count)) +
1003
+ geom_bar(stat = "identity", fill = "darkorange", alpha = 0.7) +
1004
+ labs(
1005
+ x = "Institution Code",
1006
+ y = "Number of Records",
1007
+ title = "GBIF Records by Institution Code (Isochrone Union)"
1008
+ ) +
1009
+ theme_minimal(base_size = 14) +
1010
+ theme(
1011
+ axis.text.x = element_text(angle = 45, hjust = 1, size = 12),
1012
+ axis.text.y = element_text(size = 12),
1013
+ axis.title.x = element_text(size = 14),
1014
+ axis.title.y = element_text(size = 14)
1015
+ )
1016
+ })
1017
+
1018
+ # ------------------------------------------------
1019
+ # Additional Section: mapview for species richness vs. data availability
1020
+ # ------------------------------------------------
1021
+ output$mapNUI <- renderUI({
1022
+ map_n <- mapview(cbg_vect_sf, zcol = "n", layer.name="Data Availability (n)")
1023
+ map_n@map
1024
+ })
1025
+
1026
+ output$mapSpeciesUI <- renderUI({
1027
+ map_s <- mapview(cbg_vect_sf, zcol = "n_species", layer.name="Species Richness (n_species)")
1028
+ map_s@map
1029
+ })
1030
+
1031
+ # ------------------------------------------------
1032
+ # Additional Plot: n_observations vs n_species
1033
+ # ------------------------------------------------
1034
+ output$obsVsSpeciesPlot <- renderPlot({
1035
+ # A simple scatter plot of n_observations vs. n_species from cbg_vect_sf
1036
+ ggplot(cbg_vect_sf, aes(x = log(n_observations+1), y = log(unique_species+1)) ) +
1037
+ geom_point(color = "blue", alpha = 0.6) +
1038
+ labs(
1039
+ x = "Number of Observations (n_observations)",
1040
+ y = "Number of Species (n_species)",
1041
+ title = "Data Availability vs. Species Richness"
1042
+ ) +
1043
+ theme_minimal(base_size = 14)
1044
+ })
1045
+
1046
+ # ------------------------------------------------
1047
+ # Additional Plot: Linear model of n_species ~ n_observations + median_inc + ndvi_mean
1048
+ # ------------------------------------------------
1049
+ # output$lmCoefficientsPlot <- renderPlot({
1050
+ # # Build a linear model with cbg_vect_sf
1051
+ # # Must ensure there are no NAs
1052
+ # df_lm <- cbg_vect_sf %>%
1053
+ # filter(!is.na(n_observations),
1054
+ # !is.na(unique_species),
1055
+ # !is.na(median_inc),
1056
+ # !is.na(ndvi_mean))
1057
+ #
1058
+ # if (nrow(df_lm) < 5) {
1059
+ # # not enough data
1060
+ # plot.new()
1061
+ # title("Not enough data for linear model.")
1062
+ # return(NULL)
1063
+ # }
1064
+ #
1065
+ # # Model
1066
+ # fit <- lm(unique_species ~ n_observations + median_inc + ndvi_mean, data = df_lm)
1067
+ #
1068
+ # # Using sjPlot to visualize coefficients
1069
+ # # We store in an object and then print it
1070
+ # p <- plot_model(fit, show.values = TRUE, value.offset = .3, title = "LM Coefficients: n_species ~ n_observations + median_inc + ndvi_mean")
1071
+ # print(p)
1072
+ # })
1073
+ }
1074
+
1075
+ shinyApp(ui, server)
1076
+
1077
+ # library(profvis)
1078
+ #
1079
+ # profvis({
1080
+ # shinyApp(ui, server)
1081
+ # })
R/app.R β†’ app_old.R RENAMED
File without changes
{R/rsconnect β†’ rsconnect}/shinyapps.io/diego-ellis-soto/RSF_Biodiversity_Access.dcf RENAMED
@@ -5,8 +5,9 @@ account: diego-ellis-soto
5
  server: shinyapps.io
6
  hostUrl: https://api.shinyapps.io/v1
7
  appId: 13693040
8
- bundleId: 9630454
9
  url: https://diego-ellis-soto.shinyapps.io/RSF_Biodiversity_Access/
10
  version: 1
11
  asMultiple: FALSE
12
  asStatic: FALSE
 
 
5
  server: shinyapps.io
6
  hostUrl: https://api.shinyapps.io/v1
7
  appId: 13693040
8
+ bundleId: 9631125
9
  url: https://diego-ellis-soto.shinyapps.io/RSF_Biodiversity_Access/
10
  version: 1
11
  asMultiple: FALSE
12
  asStatic: FALSE
13
+ ignoredFiles: app_old.R
rsconnect/shinyapps.io/diego-ellis-soto/SF_biodiv_access.dcf ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: SF_biodiv_access
2
+ title: SF_biodiv_access
3
+ username: diego-ellis-soto
4
+ account: diego-ellis-soto
5
+ server: shinyapps.io
6
+ hostUrl: https://api.shinyapps.io/v1
7
+ appId: 13693447
8
+ bundleId: 9631093
9
+ url: https://diego-ellis-soto.shinyapps.io/SF_biodiv_access/
10
+ version: 1
11
+ asMultiple: FALSE
12
+ asStatic: FALSE
13
+ ignoredFiles: app_old.R