在绘图中的所有坐标之间绘制线条

时间:2016-03-15 13:29:49

标签: r ggplot2

我有以下数据框:

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包中吗?

2 个答案:

答案 0 :(得分:14)

使用base绘图:

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

random_ioctl

添加铃铛和口哨。

您也可以使用FUN中的combn参数:

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])
})

答案 1 :(得分: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)

或者,您也可以在不事先添加行ID的情况下添加行ID:

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())
相关问题