标签的选择因素(ggplot2、directlabels)

Selecting factor for labels (ggplot2, directlabels)

我想使用包 directlabels 来标记我的地块。但是,我希望标签是每个点的 ID。真的没有办法 select 标记哪个因素还是我错过了?

library(ggplot2)
library(directlabels)
df <- structure(
    list(id = 1:10,
         group = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L),
         .Label = c("A", "B"),
         class = "factor"),
         value1 = c(4, 1, 6, 2, 5, 7, 3, 2, 5, 8),
         value2 = c(6, 2, 6, 2, 8, 9, 7, 5, 2, 6)
         ),
.Names = c("id", "group", "value1", "value2"),
row.names = c(NA, -10L),
class = "data.frame")

p1 <- ggplot(df, aes(x=value1, y=value2)) + geom_point(aes(colour=group))
direct.label(p1)

您必须编写自定义位置方法,如下所示:

label_all <- list( dl.trans(x = x + 0.5, y = y + 0.5), # shift every point up and right
                   gapply.fun(d) ) # include all points
direct.label(p1, method = label_all)

有关另一个示例,请参阅 the documentation,在 "Specifying the positioning method as a list" 下。

检查 the code of direct.label.ggplot() shows that geom_dl() is called in the end. This function expects an aesthetic mapping and a positioning method. The positioning method used by defaultdefault.picker("ggplot") 的 return 值,它使用调用堆栈检查,在您的情况下等同于调用 defaultpf.ggplot("point",,,)。以下对我有用:

p1 <- ggplot(df, aes(x=value1, y=value2)) +
  geom_point(aes(colour=group)) +
  geom_dl(aes(label = id), method = defaultpf.ggplot("point",,,))
p1

(请注意,您不再需要调用 direct.label()。)

directlabels包的文档确实有点少