Skip to content

Instantly share code, notes, and snippets.

@maptracker
Created January 22, 2016 18:19
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 maptracker/7260ec69e15470e369d1 to your computer and use it in GitHub Desktop.
Save maptracker/7260ec69e15470e369d1 to your computer and use it in GitHub Desktop.
Coloring the groups made by #cutree from an #R #hclust analysis (#base graphics)
## Subset of arrest data for murder and assault in the 50 US states
ma <- USArrests[, c("Murder", "Assault")]
## (FWIW, I don't think this represents a meaningful clustering of states)
## Cluster
mahc <- hclust(dist(ma), "ave")
## Cut into 6 groups
ct <- cutree(mahc, k = 6)
## Get the order of the states along the x axis
xord = mahc$labels[ mahc$order ];
## Plot the dendrogram
plot(mahc, hang = -1)
## I could not figure out how to color the labels by group. I also
## could not eliminate the labels *AND* leave enough vertical space
## for the text() call. So I will erase the labels with a box:
numStates = nrow(USArrests)
rect(-1, -100, numStates + 1, 0, col = "white", border = "white")
## Also requires hang to be -1 to assure all labels are fully below the axis
# Finally add the states in, colored by group:
text(x = 1:numStates, y = 0, label = xord,
col = ct[ xord ], srt = 90, adj = 1)
## dendextend offers a better path around some of these problems
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment