我有以下数据框:
structure(list(X1 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L,
4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L
), .Label = c("1", "2", "3", "4", "5", "6"), class = "factor"),
X2 = structure(c(1L, 6L, 8L, 10L, 12L, 13L, 3L, 4L, 1L, 6L,
7L, 9L, 10L, 12L, 13L, 3L, 4L, 5L, 10L, 12L, 13L, 4L, 1L,
6L, 12L, 13L, 3L, 1L, 6L, 7L, 8L, 10L, 11L, 12L, 13L, 2L,
3L, 11L, 12L, 13L), .Label = c("I1", "I10", "I11", "I12",
"I13", "I2", "I3", "I4", "I5", "I6", "I7", "I8", "I9"), class = "factor")), .Names = c("X1",
"X2"), row.names = c(NA, -40L), class = "data.frame")
其中 X1 是人员编号,X2 是人员所属的组。一个人可以在不同的组中。现在我想从每个人到他所属的每个组划一条线。我用plot()
这种方式解决了它:
plot(0, xlim=c(0,1), ylim=c(0,1), type="n", axes=FALSE, xlab="", ylab="")
factor.to.int <- function(f) {
(as.integer(f) - 1) / (length(levels(f)) - 1)
}
segments(factor.to.int(data$X1), 0, factor.to.int(data$X2), 1, col=data$X1)
axis(1, at = seq(0, 1, by = 1 / (length(levels(data$X1)) - 1)), labels = levels(data$X1))
axis(3, at = seq(0, 1, by = 1 / (length(levels(data$X2)) - 1)), labels = levels(data$X2))
结果如下所示:
现在我想知道如何用 ggplot2 做到这一点?
谢谢你的帮助!