这很容易使用tidyr 包,特别是该包中的gather() 函数。
首先,我创建一个我认为具有您想要的属性的数据框。请注意,我使用的是 dplyr,它很棒 pipe syntax(下面是 %>% 的东西)。
# packages we need
require(tidyr)
require(dplyr)
require(ggplot2)
# an example data frame
df <-
data.frame(var1 = rnorm(30),
var2 = rnorm(30),
A = sample(c(TRUE, FALSE), 30, replace = T),
B = sample(c(TRUE, FALSE), 30, replace = T),
C = sample(c(TRUE, FALSE), 30, replace = T),
D = sample(c(TRUE, FALSE), 30, replace = T),
E = sample(c(TRUE, FALSE), 30, replace = T)
)
关键步骤是使用tidyr::gather() 重构数据框,以便每个数据点(var1, var2) 被复制五次,即gathered 的每一列复制一次。除了复制非gathered 列中的数据外,gather() 函数还创建两个新列。其中第一个我称为class,其值为A、B、C、D 或E。第二个我称为is_in,其值为TRUE 或FALSE,具体取决于相应的数据点是否属于class 列所引用的类。
# reshape the data frame using dplyr
df.reshaped <-
df %>%
mutate(index = row_number()) %>% # number the data points
gather(class, is_in, A:E) %>% # repeat all (var1, var2) points 5x
filter(is_in == TRUE) %>% # keep only points you want
select(-is_in) # the is_in column is now superfluous
数据现在可以绘制了。只是为了验证我们的绘图将在多个方面显示相同的原始数据点,我在上面进行了mutate() 调用,以按行号对所有原始(即在收集之前)数据点进行编号。我将使用geom_text() 进行绘图,因此如果我们在不同的方面看到相同的数字,那么目标就实现了。
# plot the graph
df.reshaped %>%
ggplot(aes(x = var1, y = var2, label = index)) +
geom_text() +
facet_grid(.~class) +
theme_bw()
ggsave('SO_39820087.png', width = 10, height = 4)
结果图在我的机器上看起来像这样。