#!/usr/bin/env Rscript
fs <- read.csv("songdata.csv")
# Extract feature matrix (i.e. remove the first three columns)
f <- fs[, -(1:3)]
# Compute the principal components of the feature matrix
# Note that p$scores contains the actual loadings
p <- princomp(as.matrix(f), cor = TRUE)
# Average the first two principal components of all the songs for each
# artist into a single XY point
d <- aggregate(p$scores[, 1:2], by = list(artist = fs$artist), mean)
names(d) <- c("artist", "x", "y")
# Define the color of the region for each artist.
# First scale the X and Y coordinates of the artists to lie in [0, 1]
scale01 <- function(x) (x - min(x)) / (max(x) - min(x))
xs <- scale01(d$x)
ys <- scale01(d$y)
# Then use these as the Red and Green components, with Blue fixed at 1
artist_color <- rgb(xs, ys, 1)
# Set up a new graphics window with no borders
#dev.new(width = 10, height = 10)
png("ArtistMap.png", width=12, height=8, units="in", res=300)
par(mai = c(0, 0, 0, 0))
# Draw an empty plot
plot(d$x, d$y, type = "n")
# Load the deldir package to perform Voronoi tesselations
library(deldir)
# Compute and plot the Voronoi region for each artist
regions <- tile.list(deldir(d))
for(k in 1:length(regions)) {
polygon(regions[[k]], col = artist_color[k], lwd = 2)
}
text(d$x,d$y,d$artist)
dev.off()