John
John

Reputation: 1828

R ggplot2: add text to geom_tiles

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.

Upvotes: 5

Views: 14090

Answers (2)

LyzandeR
LyzandeR

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

enter image description here

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

Didzis Elferts
Didzis Elferts

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

enter image description here

Upvotes: 7

Related Questions