-
Notifications
You must be signed in to change notification settings - Fork 0
/
pie_maps.Rmd
2080 lines (1712 loc) · 77.9 KB
/
pie_maps.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Aquacutlure Mapping: pie & barcharts"
author: "Maggie Klope"
knit: (function(input_file, encoding) {
out_dir <- 'docs';
rmarkdown::render(input_file,
encoding=encoding,
output_file=file.path(dirname(input_file), out_dir, 'pie_maps.html'))})
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, include=FALSE}
#Loading packages
library(scatterpie)
library(janitor)
library(here)
library(USAboundaries)
library(sf)
library(tidyverse)
library(ggplot2)
library(patchwork)
library(mapview)
library(leaflet)
library(leafpop)
library(RColorBrewer)
library(leaflet.minicharts)
library(magick)
library(ggmap)
library(maps)
#remotes::install_github("flowwest/CDECRetrieve")
#library(CDECRetrieve)
library(purrr)
library(zoo)
library(ggspatial)
library(cowplot)
library(ggpubr)
library(ggrepel)
library(mapdata)
library(ggimage)
```
```{r, include=FALSE}
#data tyding and map info from Robert's markdown file
#data from Robert
data_goals <- read_csv(here("data", "data_goals.csv"))
scores_clean <- read_csv(here("data", "scores_clean.csv"))
data_scores <- full_join(data_goals, scores_clean) %>%
clean_names()
estuary_sf <- data_scores %>%
drop_na("long") %>%
st_as_sf(coords = c("long", "lat"), crs = 4326) %>%
clean_names()
#spatial data from working group
SNAPP_estuary_points <- read_sf(dsn = here("locations"), layer = "FINAL_SNAPP_ESTUARIES_POINTS-44")
high_ecology_points <- SNAPP_estuary_points %>%
filter(Ecol1 >= 0.5)
SNAPP_estuary_polygons <- read_sf(dsn = here("locations"), layer = "FINAL_SNAPP_ESTUARIES_POLYGONS-66")
# map layers from Robert's code
ca_counties <- read_sf(dsn = here("locations"), layer = "CA_counties")
or_counties <- read_sf(dsn = here("locations"), layer = "OR_counties")
wa_counties <- read_sf(dsn = here("locations"), layer = "WA_counties")
nv_counties <- read_sf(dsn = here("locations"), layer = "NV_counties")
#Reading in shapefiles for Canada and Mexico
canada <- read_sf(dsn = here("locations"), layer = "lpr_000b16a_e")
#st_crs(canada) #EPSG: 9001
# We need to reproject the Canada layer
canada <- st_transform(canada, crs = st_crs(or_counties))
mexico <- read_sf(dsn = here("locations"), layer = "mexstates")
# st_crs(mexico) #EPSG: 4326
```
### Scatterpie:
```{r scatterpie}
#Using scatterpie to put piecharts over map
#need wide format data
pie_data <- high_ecology_points %>%
select(-NCEASmap) %>%
rename(ecology = Ecol1, restoration = Resto1, harvest = Harvest1, commercial = Comm1) %>%
as.data.frame()
#using the scores from the 10 estuary/subbasins with radius proportional to Ecological score
pie_data$radius <- pie_data$ecology/2.5
Zoom_pie_1 <- ggplot() +
geom_sf(data = us_boundaries()) +
geom_sf(data = canada) +
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data,
cols = c("restoration", "harvest", "commercial"), color=NA, alpha=.8, show.legend = FALSE) +
# geom_scatterpie_legend(pie_data$radius, x=-121.5, y=49) +
coord_sf(xlim = c(-125.5, -121), ylim = c(45, 49.5)) +
theme_bw()
Zoom_pie_2 <- ggplot() +
geom_sf(data = us_boundaries()) +
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data,
cols = c("restoration", "harvest", "commercial"), color=NA, alpha=.8, show.legend = FALSE) +
# geom_scatterpie_legend(pie_data$radius, x=-119.5, y=38) +
coord_sf(xlim = c(-123.5, -119), ylim = c(34.85, 38.5)) +
theme_bw()
Zoom_pie_3 <- ggplot() +
geom_sf(data = us_boundaries()) +
geom_sf(data = mexico) +
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data,
cols = c("restoration", "harvest", "commercial"), color=NA, alpha=.8, legend_name = "Score") +
geom_scatterpie_legend(pie_data$radius, x=-119.5, y=30.5, ) +
coord_sf(xlim = c(-120, -115), ylim = c(30, 34.5)) +
theme_bw()
# put it together
Zoom_pie_ecol_rad <- Zoom_pie_1 + Zoom_pie_2 + Zoom_pie_3
ggsave("figures/final_map_pie_ecol_rad.png", Zoom_pie_ecol_rad, width = 12, height = 6, dpi = 300)
```
```{r, scatterpie all, fig.align="center", echo=FALSE}
knitr::include_graphics("figures/final_map_pie_ecol_rad.png")
```
#### Scatterpie with fixed radius
```{r scatterpied fixed}
#using a fixed radius
pie_data$radius <- .225
Zoom_pie_1_fix <- ggplot() +
geom_sf(data = us_boundaries()) +
geom_sf(data = canada) +
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data,
cols = c("ecology", "restoration", "harvest", "commercial"), color=NA, alpha=.8, show.legend = FALSE) +
coord_sf(xlim = c(-125.5, -120), ylim = c(45, 49.5)) +
theme_bw()
Zoom_pie_2_fix <- ggplot() +
geom_sf(data = us_boundaries()) +
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data,
cols = c("ecology", "restoration", "harvest", "commercial"), color=NA, alpha=.8, show.legend = FALSE) +
coord_sf(xlim = c(-123.5, -119), ylim = c(34.8, 38.5)) +
theme_bw()
Zoom_pie_3_fix <- ggplot() +
geom_sf(data = us_boundaries()) +
geom_sf(data = mexico) +
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data,
cols = c("ecology", "restoration", "harvest", "commercial"), color=NA, alpha=.8, legend_name = "Score") +
coord_sf(xlim = c(-120, -115), ylim = c(30, 34.5)) +
theme_bw()
# put it together
Zoom_pie_ecol_rad_fixed <- Zoom_pie_1_fix + Zoom_pie_2_fix + Zoom_pie_3_fix
ggsave("figures/final_map_pie_ecol_rad_fixed.png", Zoom_pie_ecol_rad_fixed, width = 12, height = 6, dpi = 300)
```
```{r, scatterpie all fixed 1, fig.align="center", echo=FALSE}
knitr::include_graphics("figures/final_map_pie_ecol_rad_fixed.png")
```
```{r}
#testing changing alpha to better view overlapping sites
high_ecology_rest_alpha <- ggplot() +
geom_sf(data = us_boundaries()) +
geom_sf(data = canada) +
geom_sf(data = mexico) +
geom_sf(data = high_ecology_points, aes(color = Resto1), size = 4, alpha = 0.75) +
coord_sf(xlim = c(-130, -115), ylim = c(30, 53)) +
scale_x_continuous(breaks = c(-130, -116)) +
scale_y_continuous(breaks = c(30, 40, 50)) +
theme_bw()
high_ecology_rest_alpha
```
#### Scatterpie with radius proportional to ecology score:
```{r projection changed - proportional radius}
# Made scatterplots round by using different map data
world_map <- map_data("world")
pie_data$radius <- pie_data$ecology/2.5
Zoom_1_round <- ggplot(world_map, aes(x = long, y = lat, group = group)) +
geom_polygon(fill="lightgray", colour = "black", lwd = 0.25)+
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data, cols = c("restoration", "harvest", "commercial"), color=NA, alpha=.8, show.legend = FALSE)+
coord_sf(xlim = c(-125.5, -121), ylim = c(45, 49.5))+
xlab("Longitude")+
ylab("Latitude")+
theme_bw()
Zoom_2_round <- ggplot(world_map, aes(x = long, y = lat, group = group)) +
geom_polygon(fill="lightgray", colour = "black", lwd = 0.25)+
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data, cols = c("restoration", "harvest", "commercial"), color=NA, alpha=.8, show.legend = FALSE)+
coord_sf(xlim = c(-123.5, -119), ylim = c(34.85, 38.5)) +
xlab("Longitude")+
ylab("Latitude")+
theme_bw()
Zoom_3_round <- ggplot(world_map, aes(x = long, y = lat, group = group)) +
geom_polygon(fill="lightgray", colour = "black", lwd = 0.25)+
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data, cols = c("restoration", "harvest", "commercial"), color=NA, alpha=.8, legend_name = "Score")+
geom_scatterpie_legend(pie_data$radius, x=-119.5, y=30.5, ) +
coord_sf(xlim = c(-120, -115), ylim = c(30, 34.5)) +
xlab("Longitude")+
ylab("Latitude")+
theme_bw()
Zooms_round <- Zoom_1_round + Zoom_2_round + Zoom_3_round
ggsave("figures/final_map_pie_ecol_rad_round.png", Zooms_round, width = 12, height = 6, dpi = 300)
```
``````{r, scatterpie all round, fig.align="center", echo=FALSE}
knitr::include_graphics("figures/final_map_pie_ecol_rad_round.png")
```
#### Updated scatterpie with fixed radius
```{r projection changed - fixed radius}
pie_data$radius <- .225
Zoom_1_fixed_round <- ggplot(world_map, aes(x = long, y = lat, group = group)) +
geom_polygon(fill="lightgray", colour = "black", lwd = 0.25)+
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data,
cols = c("ecology", "restoration", "harvest", "commercial"), color=NA, alpha=.8, show.legend = FALSE) +
coord_sf(xlim = c(-125.5, -121), ylim = c(45, 49.5))+
xlab("Longitude")+
ylab("Latitude")+
theme_bw()
Zoom_2_fixed_round <- ggplot(world_map, aes(x = long, y = lat, group = group)) +
geom_polygon(fill="lightgray", colour = "black", lwd = 0.25)+
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data,
cols = c("ecology", "restoration", "harvest", "commercial"), color=NA, alpha=.8, show.legend = FALSE) +
coord_sf(xlim = c(-123.5, -119), ylim = c(34.8, 38.5)) +
xlab("Longitude")+
ylab("Latitude")+
theme_bw()
Zoom_3_fixed_round <- ggplot(world_map, aes(x = long, y = lat, group = group)) +
geom_polygon(fill="lightgray", colour = "black", lwd = 0.25)+
geom_scatterpie(aes(x = Longitude, y = Latitude, group = Name, r = radius), data = pie_data,
cols = c("ecology", "restoration", "harvest", "commercial"), color=NA, alpha=.8, legend_name = "Score") +
coord_sf(xlim = c(-120, -115), ylim = c(30, 34.5)) +
xlab("Longitude")+
ylab("Latitude")+
theme_bw()
# put it together
Zoom_pie_ecol_rad_fixed_round <- Zoom_1_fixed_round + Zoom_2_fixed_round + Zoom_3_fixed_round
ggsave("figures/final_map_pie_ecol_rad_fixed_round.png", Zoom_pie_ecol_rad_fixed_round, width = 12, height = 6, dpi = 300)
```
```{r, scatterpie all fixed 2, fig.align="center", echo=FALSE}
knitr::include_graphics("figures/final_map_pie_ecol_rad_fixed_round.png")
```
### Leaflet Maps:
#### Using leaflet with pop-up windows of pie charts
```{r leaflet map}
#testing out leaflet map for scatterpie plots
#making leaflet using regular points
leaflet_plain <- leaflet(pie_data) %>%
addTiles() %>%
addMarkers(lng = ~Longitude,
lat = ~Latitude,
popup = ~as.character(Name),
label = ~as.character(Name))
#can add a graph in a pop-out window using popupGraph(). May work best for a Shiny App
#meaningless plot (just for testing)
test_pie <- ggplot(estuary_sf, aes(x = "", y = ecological, fill = estuary_or_subbasin))+
geom_bar(width = 1, stat = "identity", show.legend = FALSE)+
coord_polar("y", start=0)
leaflet_graph <- leaflet(pie_data) %>%
addTiles() %>%
addMarkers(lng = ~Longitude,
lat = ~Latitude,
popup = popupGraph(test_pie),
label = ~as.character(Name))
leaflet_graph
```
```{r, map with popup}
#Adding plot as a popup figure to map
#making plots & saving as svg
for( i in 1:10){
temp_data <- data_scores[i,] %>% #working on the selected row
dplyr::select(-c(lat, long, coastwide_coservation)) %>%
pivot_longer(-estuary_or_subbasin, names_to = "category", values_to = "score")
test_pie <- ggplot(temp_data, aes(x = "", y = category, fill = score))+
geom_bar(width = 1, stat = "identity", show.legend = FALSE)+
coord_polar("y", start=0)
# print(test_pie)
#ggsave(test_pie, file=paste0("figures/pie_plot_", i,".svg"), width = 14, height = 10, units = "cm")
}
#trying to view the pie plots as popups
#first tried using just one of the plots for all the points to see if it would work
mapview(estuary_sf,
popup = popupImage("/figures/pie_plot_1.svg")) #map is created, but images are broken
```
#### Using leaflet minicharts:
##### Pie charts:
```{r leaflet minicharts with picharts}
#trying leaflet.minicharts: https://cran.r-project.org/web/packages/leaflet.minicharts/vignettes/introduction.html
#need column with totals if we want to sale barcharts
#pie_data$total <- pie_data$ecology + pie_data$restoration + pie_data$harvest + pie_data$commercial
leaflet_minichart_pie <- leaflet(pie_data) %>%
addTiles() %>%
addMinicharts(lng = pie_data$Longitude, lat = pie_data$Latitude,
type = "pie",
chartdata = pie_data[,c("ecology", "restoration", "harvest", "commercial")],
#width = 60 * sqrt(pie_data$total) / sqrt(max(pie_data$total)),
transitionTime = 0)
leaflet_minichart_pie
```
##### Bar charts:
```{r leaflet minicharts with barcharts}
bar_cols <- c("#33a02c", "#b2df8a", "#1f78b4", "#a6cee3") #setting the colors for the barcharts
leaflet_minichart_bar <- leaflet(pie_data) %>%
addTiles() %>%
addProviderTiles("Esri.WorldGrayCanvas") %>% #changing background
addMinicharts(lng = pie_data$Longitude,
lat = pie_data$Latitude,
chartdata = pie_data[,c("ecology", "restoration", "harvest", "commercial")],
colorPalette = bar_cols,
width = 45, height = 45)
leaflet_minichart_bar
#setting the zoom
leaflet_minichart_bar_zoom <- leaflet(pie_data) %>%
addTiles() %>%
addProviderTiles("Esri.WorldGrayCanvas") %>% #changing background
addMinicharts(lng = pie_data$Longitude,
lat = pie_data$Latitude,
chartdata = pie_data[,c("ecology", "restoration", "harvest", "commercial")],
colorPalette = bar_cols) %>%
setView(-121.7379, 36.82495, zoom = 7)
leaflet_minichart_bar_zoom
```
##### Displaying single values:
```{r leaflet minichart with single values}
#can also represent single values as a weighted point, might be good for use in a Shiny App
leaflet_minichart_ecol <- leaflet(pie_data) %>%
addTiles() %>%
addMinicharts(
lng = pie_data$Longitude, lat = pie_data$Latitude,
chartdata = pie_data$ecol,
showLabels = TRUE,
width = 45
)
leaflet_minichart_ecol
#Adding a selector box to leaflet: unfortunately, the minichart function does not support the group argument but I was able to get basically the same result.
leaflet_points <- pie_data %>% #convert zeros to NAs so they do not get plotted on map
mutate(ecology = na_if(ecology, "0")) %>%
mutate(restoration = na_if(restoration, "0")) %>%
mutate(harvest = na_if(harvest, "0")) %>%
mutate(commercial = na_if(commercial, "0"))
point_weight = 20
leaflet_select <- leaflet(leaflet_points) %>%
addTiles() %>%
addProviderTiles("Esri.WorldGrayCanvas") %>% #changing background
addCircleMarkers(~Longitude, ~Latitude, point_weight*leaflet_points$ecology,
group = "ecology",
stroke = F,
fillOpacity = 1,
color = "darkcyan",
label = leaflet_points$ecology,
labelOptions = labelOptions(noHide = T, textOnly = TRUE, direction = "center", style = list(color = "white"))) %>%
addCircleMarkers(~Longitude, ~Latitude, point_weight*leaflet_points$restoration,
group = "restoration",
stroke = F,
fillOpacity = 1,
color = "darkcyan",
label = leaflet_points$restoration,
labelOptions = labelOptions(noHide = T, textOnly = TRUE, direction = "center", style = list(color = "white"))) %>%
addCircleMarkers(~Longitude, ~Latitude, point_weight*leaflet_points$harvest,
group = "harvest",
stroke = F,
fillOpacity = 1,
color = "darkcyan",
label = leaflet_points$harvest,
labelOptions = labelOptions(noHide = T, textOnly = TRUE, direction = "center", style = list(color = "white"))) %>%
addCircleMarkers(~Longitude, ~Latitude, point_weight*leaflet_points$commercial,
group = "commercial",
stroke = F,
fillOpacity = 1,
color = "darkcyan",
label = leaflet_points$commercial,
labelOptions = labelOptions(noHide = T, textOnly = TRUE, direction = "center", style = list(color = "white"))) %>%
addLayersControl(
baseGroups = c("ecology", "restoration", "harvest", "commercial"),
options = layersControlOptions(collapsed = FALSE)
)
leaflet_select
```
```{r test: saving leaflet image}
#testing how to save leaflet output as an image
# library(plotly)
# library(htmlwidgets)
# library(webshot)
# library(mapview)
# # first method is using webshot()
# saveWidget(leaflet_minichart_bar, "temp.html", selfcontained = FALSE)
#
# webshot("temp.html", file = "leaflet_test.png",
# cliprect = "viewport")
#
# # another method is using mapshot()
# mapshot(leaflet_minichart_bar, file = "leaflet_test.png",
# remove_controls = c("zoomControl", "layersControl", "homeButton",
# "scaleBar"))
```
### Checking centroid data against point data
```{r centroids}
#testing where the estuary polygon centroids are in relation to points (use st_centroid)
# st_geometry(SNAPP_estuary_polygons)
# SNAPP_estuary_polygons$centroid <- st_centroid(SNAPP_estuary_polygons$geometry)
#st_centroid needs projection (using NAD83/California Albers)
SNAPP_estuary_polygons_NAD83 <- SNAPP_estuary_polygons %>%
st_transform(crs = 3310)
#creating centroid data
SNAPP_estuary_polygons_centroid <- SNAPP_estuary_polygons
SNAPP_estuary_polygons_centroid$centroid <- st_centroid(SNAPP_estuary_polygons_NAD83$geometry) %>%
st_transform(crs = 4326) #converting to WSG84 to get back in lat/long
```
```{r mapping centroids}
SNAPP_estuary_centroid_points <- ggplot() +
geom_sf(data = us_boundaries()) +
geom_sf(data = canada) +
geom_sf(data = mexico) +
geom_sf(data = SNAPP_estuary_polygons_NAD83$centroid, color = "red", size = 2) +
geom_sf(data = SNAPP_estuary_points, color = "blue", size = 1.5)+
coord_sf(xlim = c(-130, -115), ylim = c(30, 53)) +
theme_void()
SNAPP_estuary_centroid_points #there is a lot of overlap, but it looks like some of the estuary centroids are not represented by the estuary points file
# I was wondering if some estuaries had multiple polygons for the same estuary:
# length(unique(SNAPP_estuary_polygons$Estuary_Na))
# 66 polygons, each for different estuaries
# length(unique(SNAPP_estuary_points$Name))
# 44 points, each for different estuaries
```
```{r, testing online example code}
# # CDEC station codes to retrieve data for
# stations = c('BDL', 'BLL', 'CSE', 'FLT', 'GOD', 'GZL', 'HON', 'HUN',
# 'IBS', 'MAL', 'MRZ', 'MSL', 'NSL', 'PCT', 'RYC', 'TEA', 'VOL')
#
# # get station locations
# station.locations = map_dfr(stations, cdec_stations) %>%
# transmute(location_id = toupper(station_id), name,
# latitude, longitude)
#
# # get station EC data
# station.data = map_dfr(stations, cdec_query, sensor_num = 100L,
# dur_code = "E", start_date = '2016-09-25',
# end_date = '2016-11-05') %>%
# group_by(
# location_id,
# datetime = as.POSIXct(round(datetime, 'hours'))
# ) %>%
# summarize(mean = mean(parameter_value, na.rm = TRUE)) %>%
# mutate(windowmean = rollmean(mean, 25, 'center')) %>%
# ungroup()
#
# # make a separate ggplot for each station
# station.plots = station.data %>%
# nest(-location_id) %>%
# mutate(plot = map2(data, location_id,
# ~ ggplot(.x) + ggtitle(.y) + theme_bw(base_size = 8) +
# aes(x = datetime, y = windowmean) + geom_line() +
# scale_x_datetime(NULL, breaks = as.POSIXct(c("2016-10-01",
# "2016-10-15", "2016-10-31")), date_labels = "%b %d",
# limits = as.POSIXct(c("2016-10-01", "2016-10-31"))) +
# scale_y_continuous("Spec. Conductivity",
# limits = c(4000, 30000))
# )
# )
#
# #get station point data
# station.points = st_as_sf(station.locations, crs = 4326,
# coords = c("longitude", "latitude")) %>%
# st_transform(3857)
#
# #create annotation
# station.annotations = station.points %>%
# bind_cols(as_tibble(st_coordinates(.))) %>%
# st_drop_geometry() %>%
# select(location_id, X, Y) %>%
# left_join(station.plots, by = "location_id") %>%
# mutate(annotation = pmap(list(X, Y, plot),
# ~ annotation_custom(ggplotGrob(..3), #convert each plot to a grob via ggplotGrob
# xmin = ..1 - 2000, xmax = ..1 + 2000, #explicitly defining the bounding box of each annotation layer.
# ymin = ..2 - 1000, ymax = ..2 + 1000))) %>%
# pull(annotation)
#
# #create map
# ggplot(station.points) +
# xlim(c(-13598000, -13563500)) +
# #annotation_map_tile(zoom = 13) +
# station.annotations
```
### Using ggplot annotation method to place barcharts on map:
#### Testing:
```{r, barcharts on map}
#Trying to overlay barcharts on a static ggplot map
bar_data <- data_scores %>%
drop_na("long") %>%
#select(-coastwide_coservation) %>%
select(estuary_or_subbasin, lat, long, ecological, harvest, community_engagement_restotation) %>%
pivot_longer(-c("estuary_or_subbasin", "lat", "long"), names_to = "category", values_to = "score")
# #normal ggplot for reference
# ggplot(data = bar_data, aes(x = category, y = score))+
# geom_bar(width = 1, stat = "identity", show.legend = FALSE)+
# facet_grid(~estuary_or_subbasin)
# make a separate ggplot for each estuary:
test_plots <- bar_data %>%
group_by(estuary_or_subbasin) %>%
nest() %>%
mutate(plot = map2(data, estuary_or_subbasin,
~ggplot(data = .x) +
aes(x = category, y = score) +
geom_bar(stat = "identity", show.legend = FALSE, aes(fill = category)) +
theme(axis.title.x=element_blank(), #removing labels
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(), #removing grids
panel.background = element_rect(fill = "transparent",colour = NA), #making backgrounds transparent
plot.background = element_rect(fill = "transparent",colour = NA),
plot.margin = unit(c(0, 0, 0, 0), "null"), #removing margins
axis.line = element_line() )#adding in black axes lines
)
)
# get spatial layer to define where the plots will be placed
plot_points <- estuary_sf %>%
select(estuary_or_subbasin, geometry)
plot_points <- st_as_sf(plot_points, crs = 4326, coords = c("longitude", "latitude")) #%>%
# st_transform(3857)
# turn the plots into annotations:
estuary_annotation <- plot_points %>%
bind_cols(as_tibble(st_coordinates(.))) %>% #retrieves coordinates in matrix form as a tibble, and binds into one dataframe
st_drop_geometry() %>% #removes geometry from sf object
left_join(test_plots, by = "estuary_or_subbasin") %>%
mutate(annotation = pmap(list( X, Y, plot), #creating an annotation column, then using the coordinates and plots in the annotation_custom() function
~annotation_custom(ggplotGrob(..3), # ..3 refers to the third argument, so plot
xmin = ..1 - 1.5, xmax = ..1 + 1.5, # ..1 refers to X
ymin = ..2 - 1, ymax = ..2 + 1))) %>% # ..2 refers to Y
pull(annotation)
# make ggplot and add list of notations
ggplot(plot_points) +
geom_sf(data = us_boundaries()) +
geom_sf(data = canada) +
xlim(c(-130, -115))+
ylim(c(30, 53))+
# coord_sf(crs = 4326, xlim = c(-13598000, -13563500), expand = FALSE)+
# annotation_map_tile(type = "osm", zoom = 13) +
estuary_annotation
```
#### Draft of barchart map of 13 high ecology sites for publication:
Using ggrepel to prevent overlap using ggrepel::repel_boxes() following example from [here](http://zachcp.org/blog/2016/ggrepelmaps/) and [here](https://github.com/slowkow/ggrepel/issues/24)
```{r, barcharts on map with offsets}
coords <- as.data.frame(st_coordinates(SNAPP_estuary_polygons_centroid$centroid)) %>%
dplyr::mutate(estuary_or_subbasin = SNAPP_estuary_polygons_centroid$Estuary_Na) %>%
rename(lat = Y, long = X) %>%
arrange(desc(lat))
bar_data <- SNAPP_estuary_polygons_centroid %>%
select(Estuary_Na, Ecol1, Restor1, Harvest1, Comm1) %>%
dplyr::filter(Ecol1 > 0.5) %>%
rename(estuary_or_subbasin = Estuary_Na) %>%
left_join(coords, by = "estuary_or_subbasin")
st_geometry(bar_data) <- NULL
coords_high_ecol <- bar_data %>%
select(estuary_or_subbasin, lat, long)
bar_data_long <- bar_data %>%
pivot_longer(-c("estuary_or_subbasin", "lat", "long"), names_to = "category", values_to = "score")
# bar_data <- data_scores %>%
# drop_na("long") %>%
# #select(-coastwide_coservation) %>%
# select(estuary_or_subbasin, lat, long, ecological, harvest, community_engagement_restotation) %>%
# pivot_longer(-c("estuary_or_subbasin", "lat", "long"), names_to = "category", values_to = "score")
point_data <- data_scores %>%
drop_na("long") %>%
select(estuary_or_subbasin, lat, long)
#' Given a Set of Points and Box sizes, find locations
#' Written by @zachp, updated by @slowkow
findboxes <- function(
df, xcol, ycol,
box_padding_x, box_padding_y,
point_padding_x, point_padding_y,
xlim, ylim,
force = 1e-7, maxiter = 20000
) {
# x and y posiitons as a dataframe
posdf <- df[c(xcol, ycol)]
# returnd a df where columns are points
boxdf <- apply(posdf, 1, function(row) {
xval <- row[xcol]
yval <- row[ycol]
return(c(
xval - box_padding_x / 2,
yval - box_padding_y / 2,
xval + box_padding_x / 2,
yval + box_padding_y / 2
))
})
# columns are x1,y1,x2,y2
boxmatrix <- as.matrix(t(boxdf))
moved <- ggrepel:::repel_boxes(
data_points = as.matrix(posdf),
point_padding_x = point_padding_x,
point_padding_y = point_padding_y,
boxes = boxmatrix,
xlim = xlim,
ylim = ylim,
hjust = 0.5,
vjust = 0.5,
force = force,
maxiter = maxiter
)
finaldf <- cbind(posdf, moved)
names(finaldf) <- c("x1", "y1", "x2", "y2")
return(finaldf)
}
# data frame with two x and two y values
df1 <- findboxes(coords_high_ecol,
xcol = "long", ycol = "lat",
box_padding_x = Reduce("-", rev(range(point_data$lat))) * .5,
box_padding_y = Reduce("-", rev(range(point_data$long))) * .55,
point_padding_x = Reduce("-", rev(range(point_data$long))) * .5,
point_padding_y = Reduce("-", rev(range(point_data$lat))) * .55,
force = 1e-3, #force = repulsion
xlim = c(-120, -112),
ylim = c(27, 55)
)
#renaming first column to match original bar_data df
colnames(df1)[1] <- "long"
#adding offset values to bar_data
bar_data_offset <- coords_high_ecol %>%
left_join(df1, by = "long") %>%
select(-c(y1)) %>% #removing repeated lat values
rename(lat_offset = y2, long_offset = x2) #renaming to be more descriptive
# taking offset lat long and creating a geometry
offset_points <- st_as_sf(bar_data_offset, crs = 4326, coords = c("long_offset", "lat_offset")) %>%
select(estuary_or_subbasin, geometry)
# make a separate ggplot for each estuary:
test_plots <- bar_data_long %>%
group_by(estuary_or_subbasin) %>%
nest() %>%
mutate(plot = map2(data, estuary_or_subbasin,
~ggplot(data = .x) +
aes(x = category, y = score) +
geom_bar(stat = "identity", show.legend = FALSE, aes(fill = category)) +
ylim(0, 1)+
theme(axis.title.x=element_blank(), #removing all labels
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(), #removing grids
panel.background = element_rect(fill = "transparent",colour = NA), #making background transparent
plot.background = element_rect(fill = "transparent",colour = NA),
plot.margin = unit(c(0, 0, 0, 0), "null"),
axis.line = element_line())
)
)
# turn the plots into annotations:
estuary_annotation <- offset_points %>%
bind_cols(as_tibble(st_coordinates(.))) %>% #retrieves coordinates in matrix form as a tibble, and binds into one dataframe
st_drop_geometry() %>% #removes geometry from sf object
left_join(test_plots, by = "estuary_or_subbasin") %>%
mutate(annotation = pmap(list( X, Y, plot), #creating an annotation column, then using the coordinates and plots in the annotation_custom() function
~annotation_custom(ggplotGrob(..3), # ..3 refers to the third argument, so plot
xmin = ..1 - 0, xmax = ..1 + 3, # ..1 refers to X
ymin = ..2 - 0, ymax = ..2 + 2))) %>% # ..2 refers to Y
pull(annotation)
#saving legend as separate object
simple_barchart <-ggplot(bar_data_long, aes(score, fill = category))+
geom_bar()+
theme(legend.margin = margin(0, 0, 0, 0))+
theme(
legend.title = element_text(size = 7),
legend.text = element_text(size = 7),
legend.background = element_rect(fill = NA))+
scale_fill_discrete(name = "Score", labels = c("Commercial Production", "Ecological", "Community Engagement Harvest", "Community Engagement Restoration"))
legend <- get_legend(simple_barchart)
gg_legend <-as_ggplot(legend)
#create final map
bar_charts_offset <- ggplot(offset_points) +
geom_sf(data = us_boundaries()) +
geom_sf(data = canada) +
xlim(c(-130, -113))+
ylim(c(27, 55))+
geom_segment(data = bar_data_offset, aes(x = long, y = lat, xend = long_offset, yend = lat_offset)) +
geom_point(data = bar_data_offset, aes(long, lat), color = "black") +
geom_point(data = bar_data_offset, aes(long_offset, lat_offset), color = "black") +
# geom_bar(data = bar_data_long, aes(score, fill = category))+
estuary_annotation +
theme_void()
# bar_charts_offset + (plot_spacer() / (gg_legend + plot_spacer() + plot_spacer())) +plot_layout(nrow=1)
layout <- c(
area(t = 1, l = 1, b = 9, r = 7),
area(t = 8, l = 1, b = 8, r = 6)
)
bar_chart_map <- bar_charts_offset + gg_legend +
plot_layout(design = layout)
bar_chart_map
```
```{r, include = FALSE}
ggsave("figures/bar_chart_map.png", bar_chart_map, width = 12, height = 6, dpi = 300)
```
Testing example from above but choosing an offset for long:
```{r, barchart on map split left and right}
#
# # Making two datasets with selecting sites from every other row
# bar_data_1 <- data_scores[seq(1, nrow(data_scores), 2), ] %>%
# drop_na("long") %>%
# select(estuary_or_subbasin, lat, long, ecological, harvest, community_engagement_restotation) %>%
# mutate(long_offset = long - 2)
#
# bar_data_2 <- data_scores[seq(2, nrow(data_scores), 2), ] %>%
# drop_na("long") %>%
# select(estuary_or_subbasin, lat, long, ecological, harvest, community_engagement_restotation) %>%
# mutate(long_offset = long + 2)
#
# #merging together
# merged_offset <- bind_rows(bar_data_1, bar_data_2) %>%
# mutate(lat_offset = lat)
#
# # taking offset lat long and creating a geometry
# offset_points <- st_as_sf(merged_offset, crs = 4326, coords = c("long_offset", "lat_offset")) %>%
# select(estuary_or_subbasin, geometry)
#
# # make a separate ggplot for each estuary:
# test_plots <- bar_data %>%
# group_by(estuary_or_subbasin) %>%
# nest() %>%
# mutate(plot = map2(data, estuary_or_subbasin,
# ~ggplot(data = .x) +
# aes(x = category, y = score) +
# geom_bar(stat = "identity", show.legend = FALSE, aes(fill = category)) +
# theme(axis.title.x=element_blank(), #removing all labels
# axis.text.x=element_blank(),
# axis.ticks.x=element_blank(),
# axis.title.y=element_blank(),
# axis.text.y=element_blank(),
# axis.ticks.y=element_blank(),
# panel.grid.major = element_blank(), panel.grid.minor = element_blank(), #removing grids
# panel.background = element_rect(fill = "transparent",colour = NA), #making background transparent
# plot.background = element_rect(fill = "transparent",colour = NA),
# plot.margin = unit(c(0, 0, 0, 0), "null"),
# axis.line = element_line())
#
# )
# )
#
# # turn the plots into annotations:
# estuary_annotation <- offset_points %>%
# bind_cols(as_tibble(st_coordinates(.))) %>% #retrieves coordinates in matrix form as a tibble, and binds into one dataframe
# st_drop_geometry() %>% #removes geometry from sf object
# left_join(test_plots, by = "estuary_or_subbasin") %>%
# mutate(annotation = pmap(list( X, Y, plot), #creating an annotation column, then using the coordinates and plots in the annotation_custom() function
# ~annotation_custom(ggplotGrob(..3), # ..3 refers to the third argument, so plot
# xmin = ..1 - 0, xmax = ..1 + 3, # ..1 refers to X
# ymin = ..2 - 0, ymax = ..2 + 2))) %>% # ..2 refers to Y
# pull(annotation)
#
# # make ggplot and add list of notations
# ggplot(offset_points) +
# geom_sf(data = us_boundaries()) +
# geom_sf(data = canada) +
# xlim(c(-130, -115))+
# ylim(c(30, 53))+
# geom_segment(data = merged_offset, aes(x = long, y = lat, xend = long_offset, yend = lat_offset)) +
# geom_point(data = merged_offset, aes(long, lat), color = "black") +
# geom_point(data = merged_offset, aes(long_offset, lat_offset), color = "black") +
# estuary_annotation
```
Testing manual offset put through the geom_boxes function:
```{r, manual offsets}
# # Making two datasets with selecting sites from every other row
# bar_data_1 <- data_scores[seq(1, nrow(data_scores), 2), ] %>%
# drop_na("long") %>%
# select(estuary_or_subbasin, lat, long, ecological, harvest, community_engagement_restotation) %>%
# mutate(long_offset = long - 2)
#
# bar_data_2 <- data_scores[seq(2, nrow(data_scores), 2), ] %>%
# drop_na("long") %>%
# select(estuary_or_subbasin, lat, long, ecological, harvest, community_engagement_restotation) %>%
# mutate(long_offset = long + 2)
#
# #merging together
# manual_offset <- bind_rows(bar_data_1, bar_data_2) %>%
# mutate(lat_offset = lat)
#
# function_offset <- findboxes(manual_offset,
# xcol = "long_offset", ycol = "lat_offset",
# box_padding_x = Reduce("-", rev(range(point_data$lat))) * .75,
# box_padding_y = Reduce("-", rev(range(point_data$long))) * .5,
# point_padding_x = Reduce("-", rev(range(point_data$long))) * 1,
# point_padding_y = Reduce("-", rev(range(point_data$lat))) * 1,
# force = 1e-2, #force = repulsion
# xlim = c(-130, -115),
# ylim = c(30, 53)
# )
#
# function_offset$estuary_or_subbasin <- manual_offset$estuary_or_subbasin
#
# function_offset_clean <- function_offset %>%
# rename(lat_offset = y2, long_offset = x2) %>%
# select(-c(x1, y1))
#
# #adding offset values to bar_data
# final_offset <- manual_offset %>%
# dplyr::select(-c(lat_offset, long_offset)) %>%
# merge(function_offset_clean, by = "estuary_or_subbasin")
#
# # taking offset lat long and creating a geometry
# final_offset_points <- st_as_sf(function_offset_clean, crs = 4326, coords = c("long_offset", "lat_offset")) %>%
# select(estuary_or_subbasin, geometry)
#
# # make a separate ggplot for each estuary:
# test_plots <- bar_data %>%
# group_by(estuary_or_subbasin) %>%
# nest() %>%
# mutate(plot = map2(data, estuary_or_subbasin,
# ~ggplot(data = .x) +
# aes(x = category, y = score) +
# geom_bar(stat = "identity", show.legend = FALSE, aes(fill = category)) +
# theme(axis.title.x=element_blank(), #removing all labels
# axis.text.x=element_blank(),
# axis.ticks.x=element_blank(),
# axis.title.y=element_blank(),
# axis.text.y=element_blank(),
# axis.ticks.y=element_blank(),
# panel.grid.major = element_blank(), panel.grid.minor = element_blank(), #removing grids
# panel.background = element_rect(fill = "transparent",colour = NA), #making background transparent
# plot.background = element_rect(fill = "transparent",colour = NA),
# plot.margin = unit(c(0, 0, 0, 0), "null"),
# axis.line = element_line())
#
# )
# )
#
# # turn the plots into annotations:
# estuary_annotation <- final_offset_points %>%
# bind_cols(as_tibble(st_coordinates(.))) %>% #retrieves coordinates in matrix form as a tibble, and binds into one dataframe
# st_drop_geometry() %>% #removes geometry from sf object
# left_join(test_plots, by = "estuary_or_subbasin") %>%
# mutate(annotation = pmap(list( X, Y, plot), #creating an annotation column, then using the coordinates and plots in the annotation_custom() function
# ~annotation_custom(ggplotGrob(..3), # ..3 refers to the third argument, so plot
# xmin = ..1 - 0, xmax = ..1 + 3, # ..1 refers to X
# ymin = ..2 - 0, ymax = ..2 + 2))) %>% # ..2 refers to Y
# pull(annotation)
#
# # make ggplot and add list of notations
# ggplot(final_offset_points) +
# geom_sf(data = us_boundaries()) +
# geom_sf(data = canada) +
# xlim(c(-130, -115))+
# ylim(c(30, 53))+
# geom_segment(data = final_offset, aes(x = long, y = lat, xend = long_offset, yend = lat_offset)) +
# geom_point(data = final_offset, aes(long, lat), color = "black") +
# geom_point(data = final_offset, aes(long_offset, lat_offset), color = "black") +
# estuary_annotation