-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSMS_figure_code.R
217 lines (170 loc) · 9.4 KB
/
SMS_figure_code.R
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
#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#
#~#~# Steph's figure stuff: a supplement to "Elevation Data Exploration"#~#~#
#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#
# Note: data objects used here are loaded in Elevation Data Exploration.R
# DR Needed to run the following code chunk to be able to install ggord
# options(repos = c(
# fawda123 = 'https://fawda123.r-universe.dev',
# CRAN = 'https://cloud.r-project.org'))
#
# # Install ggord
# install.packages('ggord')
pacman::p_load(vegan, elevatr, ggbeeswarm, ggnewscale, ggord, ggplot2, ggrepel, grid, gridExtra, raster, reshape2, sf)
library(tidyverse)
library(ggord)
library(BiocManager)
# colors
# In this order: loud pink, berry, blue, olive green, light aqua
# c("#f178fa", "#62255c", "#4d6180", "#758150", "#bafdca")
cols <- c("#f178fa", "#62255c", "#416fb4", "#799943", "#bafdca")
#### Map Figures ####
# Read in Santa Catalinas area polygon
sancat <- st_read("../../Resources/Santa_Catalina_StudyArea_Polygon_FINAL.shp")
sancat <- st_set_crs(sancat, value = 4326) # This sets the CRS to WGS84
# Obtain elevation raster for the Santa Catalinas polygon
elevation_data <- elevatr::get_elev_raster(locations = sancat, z = 9, clip = "locations")
elevation_data <- as.data.frame(elevation_data, xy = TRUE)
colnames(elevation_data)[3] <- "elevation"
# remove rows of data frame with one or more NA's,using complete.cases
elevation_data <- elevation_data[complete.cases(elevation_data), ]
# Plot: elevation map: 2 versions.
# Version 1, commented out: with new (our) data in pink and old in aqua
# Version 2, not commented out: all grey dots with black outlines
# To use one version, comment out the other!
allplot <- ggplot(data = sancat) +
geom_sf() +
coord_sf(xlim = c(-110.9643, -110.5513), ylim = c(32.27945, 32.67916), expand = FALSE) +
geom_raster(data = elevation_data, aes(x = x, y = y, fill = elevation)) +
#scale_fill_viridis_c(option = "plasma")+
scale_fill_distiller(type = "seq",
direction = -1,
palette = "Greys")+
#geom_point(data = old_data, mapping = aes(y = decimalLatitude, x = decimalLongitude), fill = "#bafdca", color = "#000000", pch = 21, size = 2) +
#geom_point(data = our_data_unique, mapping = aes(y = decimalLatitude, x = decimalLongitude), fill = "#f178fa", color = "#000000", pch = 21, size = 2)+
geom_point(data = sd_prune, mapping = aes(y = decimalLatitude, x = decimalLongitude), fill = "#d0d0d0", color = "#000000", pch = 21, size = 2)+
xlab("Longitude")+
ylab("Latitude")+
theme(legend.position = "none")
# Plot: elevation map with our data colored by habitat
# you might need this: https://gradientdescending.com/how-to-use-multiple-color-scales-in-ggplot-with-ggnewscale/
newplot_hab <- ggplot(data = sancat) +
geom_sf() +
coord_sf(xlim = c(-110.9643, -110.5513), ylim = c(32.27945, 32.67916), expand = FALSE) +
geom_raster(data = elevation_data, aes(x = x, y = y, fill = elevation)) +
scale_fill_distiller(type = "seq",
direction = -1,
palette = "Greys")+
new_scale_fill()+
geom_point(data = our_data_unique, mapping = aes(y = decimalLatitude, x = decimalLongitude, fill = habitat), pch = 21, color = "#000000", size = 3)+
scale_fill_manual(values = cols)+
xlab("Longitude")+
ylab("Latitude")
# function for extracting legend: https://stackoverflow.com/questions/11883844/inserting-a-table-under-the-legend-in-a-ggplot2-histogram
g_legend <- function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
legend
}
# extract legend: you have to do this when you have the legend included in the plot, and then remove the legend from the final grid.arrange version.
legs <- g_legend(newplot_hab)
# Final plot with no legend for grid.arrange:
newplot_hab <- newplot_hab +
theme(legend.position = "none")
# plot two maps and legend
map_fig <- grid.arrange(allplot, newplot_hab, legs, nrow = 1)
#### Boxplot figures ####
# In Dakota's exploratory code, there is code for 7 different clade-based groupings of specimens:
# Heteromyidae, Cricetidae, Sciuridae, Carnivora, Artiodactyla+Lagomorpha, Eulipotyphla, and Chiroptera.
sd_prune %>%
filter(basisOfRecord == "PRESERVED_SPECIMEN" & family %in% c("Heteromyidae", "Geomyidae")) %>%
filter(basisOfRecord == "PRESERVED_SPECIMEN" & family == "Heteromyidae") %>%
ggplot(mapping = aes(y = DEMElevationInMeters, x = scientificName)) +
geom_boxplot() +
theme_minimal()
#### Beeswarm plots ####
# These are made with two types of records: Preserved specimens and material samples.
# Not all of the species we have include reps from both our data and historical data, but that's what we want to compare with our beeswarm plots. First, we have to make a version of the data only including species that are present in both old and new data sets.
oldie.sp <- sd_prune %>%
filter(recordSource !="ASU post-2020") %>%
distinct(scientificName)
new.sp <- sd_prune %>%
filter(recordSource =="ASU post-2020") %>%
distinct(scientificName)
overlap <- intersect(oldie.sp, new.sp) # 15 species because we found R. fulvescens which is a new record
# Make a new object of only the species that both have, from the pruned object with all the data
both_prune <- sd_prune[grepl(paste(overlap$scientificName, collapse = "|"), sd_prune$scientificName),]
#check - there should be 15 species
length(unique(both_prune$scientificName)) # POW CRASH BANG!! It worked!
# Make a column for ASM or not in the pruned data. "new" is ASU post-2020, "old" is everything else.
both_prune <- both_prune %>%
mutate(newOrNot = recode(recordSource, `ASU post-2020` = "new", `non-UAZ pre-2021` = "old", `UAZ` = "old"))
# Now we make the beeswarm plots:
cri_plot <- both_prune %>%
filter(basisOfRecord == "PRESERVED_SPECIMEN"|basisOfRecord=="MATERIAL_SAMPLE") %>%
filter(order == "Rodentia"&family=="Cricetidae") %>%
ggplot(mapping = aes(x = DEMElevationInMeters, y = scientificName))+
geom_quasirandom(aes(color = newOrNot), method = "pseudorandom", size = 2)+
facet_grid(family ~ ., scales = "free_y", space = "free_y", switch = "y")+
#geom_beeswarm(aes(color = newOrNot), method = "hex")+
scale_color_manual(values = c("#62255c", "#f178fa"))+
labs(#title = "Elevational Range Comparisons",
#subtitle = "Historical surveys vs. 2020s resurvey",
x = "DEM Elevation (m)", y = "Species", color = "Record Type")
# get lengend
legs2 <- g_legend(cri_plot)
cri_plot <- cri_plot +
theme(legend.position = "none")
notcri_plot <- both_prune %>%
filter(basisOfRecord == "PRESERVED_SPECIMEN"|basisOfRecord=="MATERIAL_SAMPLE") %>%
filter(family != "Cricetidae") %>%
ggplot(mapping = aes(x = DEMElevationInMeters, y = scientificName))+
facet_grid(family ~ ., scales = "free_y", space = "free_y", switch = "y")+
geom_quasirandom(aes(color = newOrNot), method = "pseudorandom", size = 2)+
#geom_beeswarm(aes(color = newOrNot), method = "swarm")+
#geom_jitter(aes(color = newOrNot))+
#geom_violin(aes(fill = newOrNot))
scale_color_manual(values = c("#62255c", "#f178fa")) +
labs(#title = "Elevational Range Comparisons",
#subtitle = "Historical surveys vs. 2020s resurvey",
x = "DEM Elevation (m)", y = "Species", color = "Record Type") +
theme(legend.position = "none")
oldNewBees <- grid.arrange(notcri_plot, cri_plot, legs2, nrow = 1, widths = c(2,2,0.5), top = textGrob("Elevational Range Comparisons: Historical vs. 2020s resurvey",gp=gpar(fontsize=20,font=1)))
#### Corespondence analysis ####
# Make a combo item: burn + habitat, and prep the data frame to make it into a presence-absence matrix
burn <- our_data_unique %>%
mutate(burnStatus = recode(burnStatus, `Unburned` = "unburned")) %>%
mutate(habburn = paste(habitat, burnStatus, sep = " ")) %>%
dplyr::select(order, family, genus, scientificName, habburn)
# convert to presence-absence matrix
sp_pres_ab <- dcast(burn, habburn~scientificName, length)
rownames(sp_pres_ab) <- sp_pres_ab$habburn
sp_pres_ab <- sp_pres_ab %>%
dplyr::select(where(is.numeric)) %>%
mutate(across(everything(), ~ifelse(.x > 0, 1, 0)))
# Compute distance among habitats:
dis <- vegdist(sp_pres_ab, method = "bray")
pcoa <- cmdscale(dis, k = 2, eig = T)
library(ca)
corsp <- ca(sp_pres_ab)
corsp_plot <- plot(corsp)
# Make your ca plot object into a thing you can put in ggplot. From here: https://www.r-bloggers.com/2019/08/correspondence-analysis-visualization-using-ggplot/
make.ca.plot.df <- function (ca.plot.obj,
row.lab = "Rows",
col.lab = "Columns") {
df <- data.frame(Label = c(rownames(ca.plot.obj$rows),
rownames(ca.plot.obj$cols)),
Dim1 = c(ca.plot.obj$rows[,1], ca.plot.obj$cols[,1]),
Dim2 = c(ca.plot.obj$rows[,2], ca.plot.obj$cols[,2]),
Variable = c(rep(row.lab, nrow(ca.plot.obj$rows)),
rep(col.lab, nrow(ca.plot.obj$cols))))
rownames(df) <- 1:nrow(df)
df
}
corsp_df <- make.ca.plot.df(corsp_plot, row.lab = "habitat", col.lab = "species")
# NB: This looks very crappy at the moment, maybe fix it up.
corsp_niceplot <- ggplot(corsp_df, mapping = aes(x = Dim1, y = Dim2, col = Variable, label = Label))+
geom_point()+
geom_label()
corsp_niceplot
#~#~---S-A-N-D-B-O-X---~#~#-------------------