【问题标题】:R ggplot2: add text to geom_tilesR ggplot2:将文本添加到 geom_tiles
【发布时间】:2016-01-10 21:47:59
【问题描述】:

我需要显示聚类的结果。演示请看

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

我该怎么做

  1. 将具有相同聚类数的图块放在一起?
  2. 每个聚类只显示 1 个聚类数?

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

【问题讨论】:

  • 1.可以通过对states 中的因子水平重新排序来解决。

标签: r ggplot2 geom-text


【解决方案1】:

您可以使用函数reorder()根据集群更改因子水平的顺序。

df$states<-reorder(df$states,df$cluster)

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

library(plyr)
df2<-ddply(df,.(cluster),summarise,pos=mean(as.numeric(states)))

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

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

【讨论】:

    【解决方案2】:

    另一种方法是使用scale_y_discrete 设置图块的顺序,并在geom_text 上使用空白标签,每个图块只有一个标签。

    这可以解决问题:

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

    请注意,标签不会位于集群中偶数个元素的中间。它将位于您选择的位置。

    【讨论】:

      猜你喜欢
      • 2019-08-04
      • 1970-01-01
      • 2023-04-09
      • 2016-01-13
      • 1970-01-01
      • 2018-06-11
      • 2019-03-05
      • 1970-01-01
      • 2019-06-03
      相关资源
      最近更新 更多