Reputation: 1828
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.
Upvotes: 5
Views: 14090
Reputation: 37879
Another way is to use scale_y_discrete
to set the order of the tiles and use blank labels on geom_text
to just have 1 label per tile.
This can do the trick:
ggplot(df,aes(x=1,y=states,fill=factor(cluster)))+
geom_tile()+
geom_text(aes(label=c('1', '', '', '', '2', '3')))+
scale_y_discrete(limits=c("AB", "IN", "CH", "LO", "UN", "OK"))
Notice that the label won't be in the middle of an even number of elements in a cluster though. It will be in your chosen position.
Upvotes: 1
Reputation: 98459
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))
Upvotes: 7