I need to show the results of a clustering. For demo, please see
library(ggplot2)
df = data.frame(cluster=c(1,1,2,2,2,3),states=c("AB","IN","UN","CH","LO","OK"))
p2<-ggplot(df,aes(x=1,y=states,fill=factor(cluster)))+
geom_tile()+
geom_text(aes(label=cluster))
p2
How can I
My code above is reproducible and I appreciate it if you just can tweak it a little. Thanks.
You can change order of factor levels according to cluster with function reorder()
.
df$states<-reorder(df$states,df$cluster)
Then using reordered data, make new dataframe where pos
is calculated as mean position of states
that are converted to numeric.
library(plyr)
df2<-ddply(df,.(cluster),summarise,pos=mean(as.numeric(states)))
Now use new dataframe for adding labels.
ggplot(df,aes(x=1,y=states,fill=factor(cluster)))+
geom_tile()+
geom_text(data=df2,aes(y=pos,label=cluster))