Last active
April 27, 2021 21:25
-
-
Save k-hench/00f784ef24c5d381bd0732e5a07416d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
network_layout <- function(n, rotate = 0, label = NULL, weight = 2, loc = NA){ | |
tau <- seq(0, 2*pi, length.out = n+1)[1:n] + rotate | |
nodes <- tibble::tibble(idx = 1:n, | |
x = sin(tau), | |
y = cos(tau)) | |
edges <- purrr::cross_df(tibble::tibble(pop1 = nodes$idx, | |
pop2 = nodes$idx), .filter = `>=`) %>% | |
dplyr::arrange(pop1) %>% | |
dplyr::left_join(., nodes %>% select(idx, x,y) %>% purrr::set_names(., nm = c('pop1','x','y'))) %>% | |
dplyr::left_join(., nodes %>% select(idx, x,y) %>% purrr::set_names(., nm = c('pop2','xend','yend'))) %>% | |
dplyr::mutate(idx = row_number(), | |
xmid_shift = (x*weight + xend)/(1*weight+1), | |
ymid_shift = (y*weight + yend)/(1*weight+1), | |
xmid = (x+xend)/2, | |
ymid = (y+yend)/2) %>% | |
dplyr::select(idx, pop1:ymid) | |
if(!is.null(label)){ | |
nodes <- nodes %>% | |
dplyr::mutate(label = label) | |
edges <- edges %>% | |
dplyr::mutate(lab1 = label[pop1], | |
lab2 = label[pop2], | |
run = stringr::str_c(lab1,'-',lab2)) | |
} | |
tibble::tibble(loc = loc, nodes = list(nodes), edges = list(edges)) | |
} | |
plot_network <- function(loc, nodes, edges, asp = .8, sep = 0, node_lab_shift = 0){ | |
loc_edge <- c(bel = .68, hon = .66, pan = .82) -.03 | |
clr_prep <- (scales::colour_ramp(c("black", | |
"red")))(c(0.4, 1)) | |
clrs <- colorRampPalette(clr_prep)(max(edges$idx)) | |
p <- nodes %>% ggplot(aes(x, y)) + | |
coord_fixed(ratio = asp) + | |
geom_segment(data = edges, | |
aes(xend = xend, yend = yend), | |
size = .1, | |
color = "red") + | |
scale_size(limits = c(0, 1), range = c(.1, 2)) | |
for (k in nodes$idx) { | |
cat( nodes$label[k]) | |
p <- p + plot_fish(names = nodes$label[k], | |
x = nodes$x[k], y = nodes$y[k], height = .7, width = .7) | |
} | |
p + geom_label(data = edges, aes(x = xmid_shift + sign(xmid_shift) * sep, | |
y = ymid_shift + sign(ymid_shift) * sep * asp, | |
label = "x"), | |
color = "red", | |
label.padding = unit(1, "pt"), | |
label.size = 0, | |
size = 2 * .5 /ggplot2::.pt) + | |
scale_x_continuous(limits = c(-1.3, 1.3), | |
expand = c(0, 0)) + | |
scale_y_continuous(expand = c(0, 0.1)) + | |
theme_void() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment