【问题标题】:Color one point and add an annotation in ggplot2?着色一点并在ggplot2中添加注释?
【发布时间】:2012-12-30 08:53:29
【问题描述】:

我有一个包含三列的数据框a

GeneNameIndex1Index2

我画了一个这样的散点图

ggplot(a, aes(log10(Index1+1), Index2)) +geom_point(alpha=1/5)

然后我想为GeneName"G1" 的点着色,并在该点附近添加一个文本框,最简单的方法是什么?

【问题讨论】:

    标签: r dataframe ggplot2


    【解决方案1】:

    您可以创建一个仅包含该点的子集,然后将其添加到绘图中:

    # create the subset
    g1 <- subset(a, GeneName == "G1")
    
    # plot the data
    ggplot(a, aes(log10(Index1+1), Index2)) + geom_point(alpha=1/5) +  # this is the base plot
      geom_point(data=g1, colour="red") +  # this adds a red point
      geom_text(data=g1, label="G1", vjust=1) # this adds a label for the red point
    

    注意:由于每个人都在为这个问题投票,我想我会让它更容易阅读。

    【讨论】:

      【解决方案2】:

      这样的事情应该可以工作。您可能需要弄乱xy 参数到geom_text()

      library(ggplot2)
      
      highlight.gene <- "G1"
      
      set.seed(23456)
      a <- data.frame(GeneName = paste("G", 1:10, sep = ""),
                         Index1 = runif(10, 100, 200),
                         Index2 = runif(10, 100, 150))
      
      a$highlight <- ifelse(a$GeneName == highlight.gene, "highlight", "normal")
      textdf <- a[a$GeneName == highlight.gene, ]
      mycolours <- c("highlight" = "red", "normal" = "grey50")
      
      a
      textdf
      
      ggplot(data = a, aes(x = Index1, y = Index2)) +
          geom_point(size = 3, aes(colour = highlight)) +
          scale_color_manual("Status", values = mycolours) +
          geom_text(data = textdf, aes(x = Index1 * 1.05, y = Index2, label = "my label")) +
          theme(legend.position = "none") +
          theme()
      

      【讨论】:

      • @Arun 是的,你当然可以,而且对于一个真正最小的例子就足够了。我想使用数据框,因为它很容易扩展到多个标签(例如点 G1 和 G7)。不过提醒一下annotate还是不错的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 2016-08-03
      • 2019-07-29
      相关资源
      最近更新 更多