R ggplot2:向 geom_tiles 添加文本

Joh*_*ohn 3 r ggplot2 geom-text

我需要显示聚类的结果。有关演示,请参阅

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
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我怎样才能

  1. 将聚类数相同的瓦片放在一起?
  2. 每个集群只显示 1 个集群号?

我上面的代码是可重现的,如果你能稍微调整一下,我很感激。谢谢。

Did*_*rts 6

您可以根据带有函数的集群更改因子级别的顺序reorder()

df$states<-reorder(df$states,df$cluster)
Run Code Online (Sandbox Code Playgroud)

然后使用重新排序的数据,制作新的数据框,其中pos计算为states将其转换为数字的平均位置。

library(plyr)
df2<-ddply(df,.(cluster),summarise,pos=mean(as.numeric(states)))
Run Code Online (Sandbox Code Playgroud)

现在使用新的数据框来添加标签。

ggplot(df,aes(x=1,y=states,fill=factor(cluster)))+
      geom_tile()+
      geom_text(data=df2,aes(y=pos,label=cluster))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明