【问题标题】:Draw lines between all the coordinates in a plot在绘图中的所有坐标之间画线
【发布时间】:2020-01-13 02:19:06
【问题描述】:

我有以下数据框:

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

【问题讨论】:

  • “我希望在所有坐标之间画一条线”这是否意味着您希望每个点都连接到每个其他点?不确定 ggplot 是否有它,但一些图形绘图包可能在这里更好用
  • 是的,每个点都必须与其他点相连
  • 尝试igraph 包并制作一个完整的图形,然后根据您的数据框分配顶点坐标
  • 你说“蜘蛛网”暗示你需要阅读complete graphs

标签: r ggplot2


【解决方案1】:

如果您想在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())

给出:


使用过的数据:

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,而无需事先进行:

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 yanno :p
  • @MichaelChirico 我也有同样的问题 ;-)
【解决方案2】:

使用base 绘图:

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

添加花里胡哨的味道。

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

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

【讨论】:

  • @MichaelChirico 我冒昧地添加了一个“所有combn”替代方案。希望你不要介意。如果您发现它多余,只需还原编辑。
猜你喜欢
  • 2012-06-10
  • 2020-08-21
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 2022-10-25
相关资源
最近更新 更多