-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhclust_animation.R
108 lines (92 loc) · 2.77 KB
/
hclust_animation.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
# Example agglomerative hierarchical clustering
library(tidyverse)
library(gganimate)
# Generate random data
set.seed(2020)
n_groups <- 10
n_obs <- 5
df <- data.frame(
variable = rep(sample(LETTERS[1:n_groups]), each = n_obs),
id = rep(1:n_obs, n_groups),
value = sort(rnorm(n_groups * n_obs))) %>%
arrange(variable, id) %>%
mutate(id = sprintf("M%s", id))
# Convert to matrix data
mat <- df %>%
pivot_wider(names_from = "id", values_from = "value") %>%
column_to_rownames("variable") %>%
as.matrix()
# Hierarchical clustering of standardised active power
hc <- hclust(d = dist(x = mat), method = "mcquitty")
dendro <- as.dendrogram(hc)
labels <- rownames(mat)
idx <- order.dendrogram(dendro)
# Create data for animation
i <- 1
ord <- seq_along(idx)
print(labels[ord])
lst <- list()
lst[[1]] <- df %>% mutate(x = match(variable, labels))
while (i < length(idx)) {
if (ord[i] == idx[i]) {
i <- i + 1
} else{
j <- which(ord == idx[i])
tmp <- ord[i]
ord[i] <- idx[i]
ord[j] <- tmp
print(labels[ord])
lst[[length(lst) + 1]] <- df %>%
mutate(x = match(variable, labels[ord]))
}
}
data <- lst %>%
setNames(seq_along(lst)) %>%
bind_rows(.id = "Iteration") %>%
mutate(Iteration = sprintf("Step %s", Iteration))
# Static base plot
gg_base <- ggplot(data, aes(x, id, fill = value, group = variable)) +
geom_tile() +
geom_text(
data = data %>%
group_by(Iteration) %>%
distinct(variable, x) %>%
ungroup() %>%
mutate(value = 0, id = ""),
aes(x = x, y = -0.5, label = variable, group = variable),
hjust = 0.5,
size = 4.5) +
theme_minimal() +
coord_cartesian(clip = "off") +
scale_fill_distiller(palette = "RdBu") +
theme(
panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
axis.ticks.x = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_text(size = 12),
legend.position = "bottom") +
labs(x = "", y = "")
# Make sure everything looks ok before animating
#gg_base +
# facet_wrap(~ Iteration, scale = "free_x")
# Animate
anim_plot <- gg_base +
ggtitle("{closest_state}") +
transition_states(
Iteration,
transition_length = 1,
state_length = 1,
wrap = FALSE) +
exit_fly(x_loc = 0, y_loc = 0) +
enter_fly(x_loc = 0, y_loc = 0) +
theme(plot.title = element_text(size = 16))
# Save animation as animated GIF
animate(
anim_plot,
nframes = 150,
width = 960, width = 540, units = "px",
end_pause = 50,
renderer = gifski_renderer("animation.gif"))