Skip to content

Instantly share code, notes, and snippets.

@jalapic
Created April 6, 2015 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jalapic/e3540599de8549f6c2ca to your computer and use it in GitHub Desktop.
Save jalapic/e3540599de8549f6c2ca to your computer and use it in GitHub Desktop.
#### Multidimensional Scaling aka Principal Coordinates Analysis
# Multidimensional scaling takes a set of dissimilarities and returns a set of points such that the
# distances between the points are approximately equal to the dissimilarities.
### Example 1 - from rbloggers - http://www.r-bloggers.com/multidimensional-scaling-mds-with-r/
#get data
dist.au <- read.csv("http://rosetta.reltech.org/TC/v15/Mapping/data/dist-Aus.csv")
dist.au
#tidy up
row.names(dist.au) <- dist.au[, 1]
dist.au <- dist.au[, -1]
dist.au #note - this is already a dissimilarity matrix
#if your data are not in a dissimilarity matrix, you need to make one with dist()
# Multidimensional Scaling (MDS) with function cmdscale()
fit <- cmdscale(dist.au, eig = TRUE)
fit
x <- fit$points[, 1]
y <- fit$points[, 2]
plot(x, y, pch = 19, xlim = range(x) + c(0, 600))
city.names <- c("Adelaide", "Alice Springs", "Brisbane", "Darwin", "Hobart",
"Melbourne", "Perth", "Sydney")
text(x, y, pos = 4, labels = city.names)
#flip axes in base r
x <- 0 - x
y <- 0 - y
plot(x, y, pch = 19, xlim = range(x) + c(0, 600))
text(x, y, pos = 4, labels = city.names)
#using igraph layout
library(igraph)
g <- graph.full(nrow(dist.au))
V(g)$label <- city.names
layout <- layout.mds(g, dist = as.matrix(dist.au))
plot(g, layout = layout, vertex.size = 3)
### Additional bit: Plotting with ggplot2
library(ggplot2)
df <- data.frame(x,y)
df
ggplot(df, aes(x,y)) +
geom_point(size=4) +
geom_text(label=city.names, hjust=-0.15) +
xlim(-2000, 2000)
#### Example 2 - http://gastonsanchez.com/blog/how-to/2013/01/23/MDS-in-R.html
# convert eurodist to matrix
euromat = as.matrix(eurodist) #already a dist object
# inspect first five elements
euromat[1:5, 1:5]
cmdscale(d, k = 2, eig = FALSE, add = FALSE, x.ret = FALSE)
# 1) MDS 'cmdscale'
mds1 = cmdscale(eurodist, k = 2)
# plot
plot(mds1[,1], mds1[,2], type = "n", xlab = "", ylab = "", axes = FALSE,
main = "cmdscale (stats)")
text(mds1[,1], mds1[,2], labels(eurodist), cex = 0.9, xpd = TRUE)
#### Example 3. Non-metric Multidimensional Scaling
library(MASS)
d <- dist(dist.au)
isoMDS(d)
isoMDS(d, k=3)
isoMDS(d, k=4)
res<-NULL
for(i in 1:5){
res[[i]] <- isoMDS(d, k=i)[[2]]
}
plot(1:5, res)
fit <- isoMDS(d, k=3)
x <- fit$points[,1]
y <- fit$points[,2]
plot(x, y, xlab="Coordinate 1", ylab="Coordinate 2",
main="Nonmetric MDS", type="n")
text(x, y, labels = city.names, cex=.7, col="purple")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment