-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathCentroid-Vectors.Rmd
230 lines (163 loc) · 7.99 KB
/
Centroid-Vectors.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
---
title: "Vector Statistics on Centroids"
author: "Andrew L Jackson"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Vector Statistics on Centroids}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
```{r setup, echo = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>",
fig.width = 6, fig.height = 5)
library(viridis)
palette(viridis(3))
```
## Load up some data to illustrate the vector-based metrics
We will use the same demo data as per the main introductory vignette. We plot it just to remind us.
```{r load-data}
# remove previously loaded items from the current environment and remove previous graphics.
rm(list=ls())
graphics.off()
# Here, I set the seed each time so that the results are comparable.
# This is useful as it means that anyone that runs your code, *should*
# get the same results as you, although random number generators change
# from time to time.
set.seed(1)
library(SIBER)
library(ggplot2)
library(magrittr) # to enable piping
library(dplyr)
# load in the included demonstration dataset
data("demo.siber.data")
#
# create the siber object
siber.example <- createSiberObject(demo.siber.data)
# Create lists of plotting arguments to be passed onwards to each
# of the three plotting functions.
community.hulls.args <- list(col = 1, lty = 1, lwd = 1)
group.ellipses.args <- list(n = 100, p.interval = 0.95, lty = 1, lwd = 2)
group.hull.args <- list(lty = 2, col = "grey20")
par(mfrow=c(1,1))
plotSiberObject(siber.example,
ax.pad = 2,
hulls = F, community.hulls.args,
ellipses = T, group.ellipses.args,
group.hulls = T, group.hull.args,
bty = "L",
iso.order = c(1,2),
xlab = expression({delta}^13*C~'permille'),
ylab = expression({delta}^15*N~'permille')
)
```
As before, we fit the Bayesian model describing the ellipses.
```{r fit-mvn}
# options for running jags
parms <- list()
parms$n.iter <- 2 * 10^4 # number of iterations to run the model for
parms$n.burnin <- 1 * 10^3 # discard the first set of values
parms$n.thin <- 10 # thin the posterior by this many
parms$n.chains <- 2 # run this many chains
parms$save.output = FALSE
parms$save.dir = tempdir()
# define the priors
priors <- list()
priors$R <- 1 * diag(2)
priors$k <- 2
priors$tau.mu <- 1.0E-3
# fit the ellipses which uses an Inverse Wishart prior
# on the covariance matrix Sigma, and a vague normal prior on the
# means. Fitting is via the JAGS method.
ellipses.posterior <- siberMVN(siber.example, parms, priors)
```
## Introducing the vector-based statistics.
Now we can extract the centroid data and plot the vector data.
```{r extract-centroids}
# extract the centroids from the fitted model object
centroids <- siberCentroids(ellipses.posterior)
# calculate pairwise polar vectors among all groups
# this is not actually used in this example
angles_distances <- allCentroidVectors(centroids, do.plot = FALSE)
```
<!-- We could if we want only compare specific pairs of groups by defining the combinations here (code below not run in this example). -->
<!-- ```{r specific-vectors, eval = FALSE} -->
<!-- # here we define the character vector of pairwise names so that we -->
<!-- # only compare between pre-monsoon and monsoon data for the same -->
<!-- # species -->
<!-- paired.names <- paste0(paste0(siber.example$all.communities[2], ".", -->
<!-- siber.example$group.names[[1]]), "|", -->
<!-- paste0(siber.example$all.communities[1], ".", -->
<!-- siber.example$group.names[[1]])) -->
<!-- # use this new function to calculate only these specific comparisons -->
<!-- angles_distances <- specificCentroidVectors(centroids, -->
<!-- paired.names, do.plot = FALSE) -->
<!-- ``` -->
The posterior distributions of the angles can then be visualise as a polar histograms, since the data wrap between $-\pi$ and $\pi$. For some reason, I cant get the gridline associate with $\pi$ to appear.
```{r ggplot-polar, fig.width=9}
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# function to do the histograms on each group
my.hist <- function(df){
test <- hist(df$angles,
breaks = seq(from = -pi, to = pi, length = 60),
plot = FALSE)
X <- data.frame(counts = test$counts, mids = test$mids, dens = test$density,
counts.stdzd = test$counts / max(test$counts))
return(X)
}
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# calculate the points for each group's ellipse
hist.by.groups <- angles_distances %>% group_by(comparison) %>%
do(my.hist(.))
all.roses <- ggplot(data = hist.by.groups, aes(x = mids, y = counts.stdzd)) +
geom_bar(stat = "identity") +
coord_polar(start = pi / 2, direction = -1) +
facet_wrap( ~ comparison) +
theme(axis.ticks.y = element_blank(),
axis.text.y = element_blank()) +
scale_x_continuous( breaks = c(-pi, -pi/2, 0, pi/2, pi),
labels = c("","-\u03C0/2","0","\u03C0/2", "\u03C0"))
print(all.roses)
```
## Polar density plots
Try some fancy 2-d density plots. These boxes represent the density of the tips of the polar vectors describing the relative position between pairs of individuals. The median vector is shown as an arrow, with the 2-dimensional heatmaps showing where the tip is likely to be. To do this, we have to convert our polar coordinates to cartesian space using the formulae: $(x,y) = (r\cos(\theta),r\sin(\theta))$.
The names for each comparison are not the prettiest or most informative. Here the "X" is superfluous and has appeared via the dplyr code above. The panel label 'X1.1.1.2' reads as community 1 group 1, compared with community 1 group 2. You could relabel the groups in the field `cart_positions$comparison` below.
```{r polar-density, fig.width = 10, fig.height = 7 }
median_vectors <- dplyr::summarise(group_by(angles_distances, comparison),
medAngle = median(angles), medDist = median(distances))
origins <- data.frame(comparison = median_vectors$comparison,
x = 0, y = 0)
ends <- with(median_vectors, data.frame(comparison = comparison,
x = medDist * cos(medAngle),
y = medDist * sin(medAngle)))
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# generate the start and end points of the medians for the arrows
for_arrows <- dplyr::bind_rows(origins, ends)
# rename the comparison label for nice plot labels below
# aa <- unlist(strsplit(as.character(for_arrows$comparison), "[.]"))
# aa <- aa[seq(3,length(aa),5)]
# for_arrows$comparison2 <- factor(aa)
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# create the cartesian points for the estimated tips of the arrows
cart_positions <- with(angles_distances, data.frame(x = distances * cos(angles),
y = distances * sin(angles),
comparison = comparison ))
# rename as above
# bb <- unlist(strsplit(as.character(angles_distances$comparison), "[.]"))
# bb <- bb[seq(3,length(bb),5)]
# cart_positions$comparison2 <- factor(bb)
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# plot it
ggplot(cart_positions, aes(x,y) ) +
geom_bin2d(bins = 20) +
scale_fill_gradient(low = "white", high = "black") +
coord_cartesian(xlim = c(-20, +20), ylim = c(-20, +20)) +
facet_wrap( ~ comparison, scales = "fixed") +
theme_classic() +
geom_path(data = for_arrows,
arrow = arrow(type = "open", length = unit(0.2, "cm")),
col = "red", alpha = 0.6) +
ylab(expression(paste(delta^{15}, "N (permille)"))) +
xlab(expression(paste(delta^{13}, "C (permille)"))) +
theme(text = element_text(size=15))
```