Created
September 3, 2016 13:42
-
-
Save talegari/687be1db2605ec7534e1d489d90ecab1 to your computer and use it in GitHub Desktop.
Two dimensional multi dimensional scaling (MDS) plot
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
################################################################################ | |
# | |
# mds_2d_plot ---- | |
# | |
################################################################################ | |
# | |
# author : talegari (Srikanth KS) | |
# license : GNU AGPLv3 (http://choosealicense.com/licenses/agpl-3.0/) | |
# | |
################################################################################ | |
# | |
# Two dimensional multi dimensional scaling (MDS) plot | |
# | |
# Arguments ---- | |
# | |
# mat : an integer or numeric matrix | |
# color_by : factor of same length as number of rows of mat. NULL by default. | |
# | |
# Value ---- | |
# | |
# A ggplot object | |
# | |
# Imports/Depends ---- | |
# | |
# Packages `ggplot2`, `assertthat` | |
# | |
mds_2d_plot <- function(mat, color_by = NULL){ | |
assertthat::assert_that(is.matrix(mat) && | |
typeof(mat) %in% c("integer", "double") | |
) | |
if(!is.null(color_by)){ | |
assertthat::assert_that(is.factor(color_by)) | |
assertthat::assert_that(length(color_by) == nrow(mat)) | |
} | |
mat_2d <- as.data.frame(cmdscale(dist(mat), k = 2)) | |
colnames(mat_2d) <- c("dim_1", "dim_2") | |
if(!is.null(color_by)){ | |
pic <- ggplot2::qplot(dim_1 | |
, dim_2 | |
, data = mat_2d | |
, color = color_by | |
, xlab = NULL | |
, ylab = NULL) + | |
ggplot2::geom_point(alpha = 0.5) | |
} else{ | |
pic <- ggplot2::qplot(dim_1 | |
, dim_2 | |
, data = mat_2d | |
, xlab = NULL | |
, ylab = NULL) + | |
ggplot2::geom_point(alpha = 0.5) | |
} | |
return(pic) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment