R ggplot2: add text to geom_tiles

John picture John · Oct 13, 2015 · Viewed 8.1k times · Source

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

enter image description here

How can I

  1. Put the tiles with the same clustering number together?
  2. Show only 1 clustering number per cluster?

My code above is reproducible and I appreciate it if you just can tweak it a little. Thanks.

Answer

Didzis Elferts picture Didzis Elferts · Oct 13, 2015

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))

enter image description here