# [R] hclust and ggplot2

wwreith reith_william at bah.com
Wed Dec 14 03:14:49 CET 2011

```I saw an example online of taking hclust dendrogram and plotting it using
ggplot2 and thought I would give it a try to see what it would look like. I
get an error when trying to use ggplot; Error: ggplot2 doesn't know how to
deal with data of class phylo. Regular plot works fine but I can't get
ggplot2 to work.

see code below....

rows=100
columns=100

#create matrix
all=matrix(nrow=rows, ncol=columns)
#initialize first column
all[,1]=rbinom(rows,1,.5)
#set probability
probv=.9

for (j in 2:columns)
{
for (i in 1:rows)
{
#set the probability based on the values in the columns to the left
if (all[i,j-1]==1)
{all[i,j]=rbinom(1,1,1-probv)}
else {all[i,j]=rbinom(1,1,probv)}
}
}
#make the first row an outlier
all[5,]=rbinom(columns,1,.1)
all[4,]=rbinom(columns,1,.1)
all[3,]=rbinom(columns,1,.1)
all[2,]=rbinom(columns,1,.1)
all[1,]=rbinom(columns,1,.1)
all[6:9,]=rbinom(columns,1,.1)
all[10:19,]=rbinom(columns,1,.3)
all[20:29,]=rbinom(columns,1,.7)

#1 to 10 .5 11 to 89 .9 .1 90 columns
#calculate the distances for clustering
rand1=dist(all)
#cluster on those distances and plot
hc1=hclust(rand1,"average")
plot(hc1)

## now plot using ggplot and polar coordinates. Line starting
p<-ggplot(data=x) yields the error. This is the online code I found.
library(ape)
library(cluster)
library(ggplot2)
x <- as.phylo(hc1)
p <- ggplot(data=x)
p <- p + geom_segment(aes(y=x,x=y,yend=xend,xend=yend),
colour="blue",alpha=1)
p <- p + geom_text(data=label.phylo(x), aes(x=y, y=x, label=label),family=3,
size=3) + xlim(0, xlim) + coord_polar()

theme <- theme_update(  axis.text.x = theme_blank(),
axis.ticks = theme_blank(),
axis.title.x = theme_blank(),
axis.title.y = theme_blank(),
legend.position = "none"
)
p <- p + theme_set(theme)
print(p)

--
View this message in context: http://r.789695.n4.nabble.com/hclust-and-ggplot2-tp4193353p4193353.html
Sent from the R help mailing list archive at Nabble.com.

```