【问题标题】:Change dots of a ggplot to text labels将 ggplot 的点更改为文本标签
【发布时间】:2013-05-02 21:24:35
【问题描述】:

最近我向question 询问有关在一张图片中获取多个图表的问题。我得到了一些很好的答案,但仍然存在 1 个问题。

如何将散点图中的点更改为标签? 剧情长这样

现在我希望将所有黑点更改为数据的行名。 我用于绘图的代码如下:

plotAll<-function(data){
  combs <- expand.grid(names(data), names(data))
  out <- do.call(rbind, apply(combs, 1, function(x) {
    tt <- data[, x]; names(tt) <- c("V1", "V2")
    tt <- cbind(tt, id1 = x[1], id2 = x[2])
  }))

  library(plyr)
  df.text=ddply(out[out$id1==out$id2,],.(id1,id2),summarise,
                pos=max(V1)-(max(V1)-min(V1))/2)
  out[out$id1==out$id2,c("V1","V2")]<-NA
  ggplot(data = out, aes(x = V2, y = V1)) + geom_point(alpha = 0.5) +
    facet_grid(id1 ~ id2,scales="fixed")+
    geom_text(data=df.text,aes(pos,pos,label=id1)) + geom_abline( slope=1 ) + 
    ggtitle("Corralation between measured & calculated affinities") +
    ylab("") + xlab("") + theme(panel.grid.minor.x=element_blank(), panel.grid.major.x=element_blank())
}

我知道我必须将geom_point(alpha=0.5) 的设置更改为geom_text(label=rownames(data)) 但这会删除我的轴并将行名放在y 轴和我的数据点上。所以可能我在情节的布局上做错了什么,但它是什么仍然是一个问题。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    所以结果比我想象的要困难得多...基本问题是 NA 值 - geom_text 无法处理它们。这样做很容易解决:

    geom_text(data = out[!is.na(out$V1),], label = "test")
    

    但是,当您将 rownames 作为标签时,它会出现问题。我不知道为什么,但通过向您的数据框添加标签列来快速解决它。完整功能如下。

    plotAll<-function(data){
      combs <- expand.grid(names(data), names(data))
      out <- do.call(rbind, apply(combs, 1, function(x) {
        tt <- data[, x]; names(tt) <- c("V1", "V2")
        tt <- cbind(tt, id1 = x[1], id2 = x[2])
      }))
    
      library(plyr)
      df.text=ddply(out[out$id1==out$id2,],.(id1,id2),summarise,
                    pos=max(V1)-(max(V1)-min(V1))/2)
      out[out$id1==out$id2,c("V1","V2")]<-NA
      out$labels <- rownames(out)
      ggplot(data = out, aes(x = V2, y = V1)) + geom_text(data = out[!is.na(out$V1),], aes(label = labels)) +
        facet_grid(id1 ~ id2,scales="fixed")+
        geom_text(data=df.text,aes(pos,pos,label=id1)) + geom_abline( slope=1 ) + 
        ggtitle("Corralation between measured & calculated affinities") +
        ylab("") + xlab("") + theme(panel.grid.minor.x=element_blank(), panel.grid.major.x=element_blank())
    }
    plotAll(data)
    

    【讨论】:

    • 是的,这正是我的预期。但是这样做给了我:错误:美学的长度必须为一,或与 dataProblems:rownames(data) 的长度相同
    • 是的...在从您的其他问题中获取数据后,我现在正在查看它 - 我会尽快回复您!
    • 我认为这是facet_grid() 中的内容。如果您将公式更改为~ v2,那就很高兴了。
    • @SanderVanderZeeuw 让我知道新答案是否适合您
    • 抱歉回复晚了。我会马上检查的
    猜你喜欢
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    相关资源
    最近更新 更多