Created
April 3, 2024 13:21
-
-
Save friendly/9d07fbfdd7a0543ce8b57bcadafa2d8e to your computer and use it in GitHub Desktop.
Animation of PCA vs. tSNE dimension reduction
This file contains hidden or 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
#' --- | |
#' title: Animate transition from PCA <--> tsne | |
#' --- | |
# idea from: https://jef.works/genomic-data-visualization-2024/blog/2024/03/06/akwok1/ | |
#' ## Load packages and data | |
library(ggplot2) | |
library(gganimate) | |
library(Rtsne) | |
library(patchwork) | |
data(Diabetes, package="heplots") | |
#' ## PCA | |
diab.pca <- prcomp(Diabetes[, 1:5], scale = TRUE, rank.=2) | |
df1 <- data.frame(diab.pca$x, group = Diabetes$group) | |
colnames(df1) <- c("Dim1", "Dim2", "group") | |
df1 <- cbind(df1, method="PCA") | |
p1 <- ggplot(df1, aes(x=Dim1, y=Dim2, color=group, shape=group)) + | |
geom_point(size = 3) + | |
stat_ellipse(level = 0.68, linewidth=1.1) + | |
geom_hline(yintercept = 0) + | |
geom_vline(xintercept = 0) + | |
labs(x = "Dimension 1", | |
y = "Dimension 2") + | |
ggtitle("PCA") + | |
theme_bw(base_size = 16) + | |
theme(legend.position = "bottom") | |
p1 | |
#' ## tSNE: nonlinear dimensionality reduction | |
set.seed(123) | |
diab.tsne <- Rtsne(Diabetes[, 1:5], scale = TRUE) | |
df2 <- data.frame(diab.tsne$Y, group = Diabetes$group) | |
colnames(df2) <- c("Dim1", "Dim2", "group") | |
df2 <- cbind(df2, method="tSNE") | |
p2 <- ggplot(df2, aes(x=Dim1, y=Dim2, color = group, shape=group)) + | |
geom_point(size = 3) + | |
stat_ellipse(level = 0.68, linewidth=1.1) + | |
geom_hline(yintercept = 0) + | |
geom_vline(xintercept = 0) + | |
labs(x = "Dimension 1", | |
y = "Dimension 2") + | |
ggtitle("tSNE") + | |
theme_bw(base_size = 16) + | |
theme(legend.position = "bottom") | |
p2 | |
p1 + p2 | |
#' ## Make an animated plot showing transitions between the PCA representation and the tsne one | |
df3 <- rbind(df1, df2) | |
animated_plot <- | |
ggplot(df3, aes(x=Dim1, y=Dim2, color=group, shape=group)) + | |
geom_point(size = 3) + | |
stat_ellipse(level = 0.68, linewidth=1.1) + | |
geom_hline(yintercept = 0) + | |
geom_vline(xintercept = 0) + | |
labs(title = "PCA vs. tSNE Dimension Reduction: {closest_state}", | |
subtitle = "Frame {frame} of {nframes}", | |
x = "Dimension 1", | |
y = "Dimension 2") + | |
transition_states( method, transition_length = 2, state_length = 3 ) + | |
view_follow() + | |
theme_bw(base_size = 16) + | |
theme(legend.position = "bottom") | |
animated_plot | |
anim_save("diabetes-pca-tsne.gif", animated_plot, path="images/") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment