在ggplot2中如何给一个点上色并添加注释?

21

我有一个名为a的数据框,包含三列:

GeneNameIndex1Index2

我画了一个散点图,就像这样:

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

那么我想给一个 GeneName"G1" 的点上色,并在该点附近添加一个文本框,最简单的方法可能是什么?

2个回答

55

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

# 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

注意:由于每个人都在投票支持此问题,我认为我可以让它更容易阅读。


24

类似这样的东西应该可以工作。您可能需要在geom_text()xy参数上进行调整。

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

屏幕截图


1
@Arun 是的,当然你可以这样做,对于一个真正最小的例子来说,那已经足够了。我想使用数据框,因为它可以轻松扩展到多个标签(例如点G1和G7)。但是被提醒使用annotate也是很好的。 - SlowLearner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接