2011-04-03 140 views
24

有没有方法可以将标签添加到绘图中的每个点?我在一个图像编辑器上做了这个以传达这个想法:1如何将标签添加到绘图

qplot(pcomments, gcomments , data = topbtw, colour = username)

Manually added fake labels to qplot

回答

27

要在Andrie的出色答卷跟进,我经常使用两种方法来标签添加到如果我需要突出显示特定数据,则在图上的点的子集。两者如下所示:

dat <- data.frame(x = rnorm(10), y = rnorm(10), label = letters[1:10]) 

#Create a subset of data that you want to label. Here we label points a - e 
labeled.dat <- dat[dat$label %in% letters[1:5] ,] 

ggplot(dat, aes(x,y)) + geom_point() + 
    geom_text(data = labeled.dat, aes(x,y, label = label), hjust = 2) 

#Or add a separate layer for each point you want to label. 
ggplot(dat, aes(x,y)) + geom_point() + 
    geom_text(data = dat[dat$label == "c" ,], aes(x,y, label = label), hjust = 2) + 
    geom_text(data = dat[dat$label == "g" ,], aes(x,y, label = label), hjust = 2) 
+3

+1为了突出显示仅标记子集通常是有意义的,异常值。 – Andrie 2011-04-04 13:34:44

14

是,使用geom_text()将文本添加到您的情节:

原来与生成。这里有一个例子:

library(ggplot2) 

qplot(mtcars$wt, mtcars$mpg, label=rownames(mtcars), geom="text") 

ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars))) + geom_text(size=3) 

见在线文档的详细信息:http://had.co.nz/ggplot2/geom_text.html

enter image description here