2016-03-15 52 views
5

我有以下数据框:画出所有坐标之间线路的情节

data <- data.frame(x = c(5,1,3,2,5,7,12), y = c(5,7,6,1,3,5,6)) 

我可以用ggplot功能绘制这些坐标,绘制这些坐标之间的一条线:

ggplot(data, aes(x, y)) + geom_point(size = 3) + geom_line() 

所以远远没有问题。但是,通过坐标而不是一条线,我想要在所有坐标之间画一条线。在所有坐标之间创建一种蜘蛛网。这可能在ggplot2包中吗?

+1

“我想要一条线的所有坐标之间绘制”这是否意味着你希望每一个单点连接到所有其他点? 不确定ggplot是否有它,但有些图形绘制软件包在这里可能更好用 – Marsenau

+0

是的,每一个点都必须连接到其他每个点 – Jelmer

+1

尝试使用'igraph'软件包并制作完整的图形,然后指定顶点根据你的数据帧的坐标 –

回答

13

如果你想在ggplot2中这样做,那么你可以使用geom_segment这个。但在你做出这样的情节之前,你必须创建一个数据框,将每个观察结果与其他观察结果连接起来。

library(ggplot2) 
library(dplyr) 
library(tidyr) 
dat %>% 
    complete(nesting(x,y), id) %>%  # create the combinations 
    select(id, xend=x, yend=y) %>%  # rename the new variables as end-points 
    left_join(dat, ., by = 'id') %>%  # join with the original dataframe 
    filter(!(x==xend & y==yend)) %>%  # remove the endpoints that are the same as the start points 
    ggplot(., aes(x, y)) + 
    geom_segment(aes(x = x, y = y, xend = xend, yend = yend)) + 
    geom_label(aes(x = x, y = y, label = id, color = factor(id)), show.legend = FALSE) + 
    theme_minimal(base_size = 14) + 
    theme(axis.title = element_blank()) 

这给:可以按如下方式处理它

enter image description here


使用的数据:

dat <- data.frame(x = c(5,1,3,2,5,7,12), y = c(5,7,6,1,3,5,6)) 
dat$id <- 1:nrow(dat) 

另外,您还可以添加该行 - 没有这样做事先:

dat %>% 
    mutate(id = row_number()) %>%  # add a row id 
    complete(nesting(x,y), id) %>%  # create the combinations 
    select(id, xend=x, yend=y) %>%  # rename the new variables as end-points 
    left_join(dat %>% mutate(id = row_number()), ., 
      by = 'id') %>%    # join with the original dataframe (also with an added row id) 
    filter(!(x==xend & y==yend)) %>%  # remove the endpoints that are the same as the start points 
    ggplot(., aes(x, y)) + 
    geom_segment(aes(x = x, y = y, xend = xend, yend = yend)) + 
    geom_label(aes(x = x, y = y, label = id, color = factor(id)), show.legend = FALSE) + 
    theme_minimal(base_size = 14) + 
    theme(axis.title = element_blank()) 
+1

甚至fancier :)我不能给out +1再次yanno:p – MichaelChirico

+0

@MichaelChirico我有同样的问题;-) – Jaap

14

使用base绘图:

plot(data) 
sapply(combn(nrow(data), 2, simplify = FALSE), 
     function(x) do.call("segments", as.list(c(t(data[x,]))))) 

enter image description here

添加花里胡哨的味道。

您也可以使用在combnFUN说法:

plot(data) 
combn(nrow(data), 2, simplify = FALSE, FUN = function(cm){ 
    segments(x0 = data[cm[1], 1], 
      y0 = data[cm[1], 2], 
      x1 = data[cm[2], 1], 
      y1 = data[cm[2], 2]) 
}) 
+3

@MichaelChirico我冒昧地添加'all' combn''替代品。希望你不介意。只要恢复编辑,如果你发现它是多余的。 – Henrik