我有以下数据帧:
data <- data.frame(x = c(5,1,3,2,5,7,12), y = c(5,7,6,1,3,5,6))
Run Code Online (Sandbox Code Playgroud)
我可以使用ggplot函数绘制这些坐标,并在这些坐标之间绘制一条直线:
ggplot(data, aes(x, y)) + geom_point(size = 3) + geom_line()
Run Code Online (Sandbox Code Playgroud)
到目前为止,没有问题.但是通过坐标而不是单行,我希望在所有坐标之间绘制一条线.在所有坐标之间创建一种蜘蛛网.ggplot2包裹中有可能吗?
Mic*_*ico 14
使用base绘图:
plot(data)
sapply(combn(nrow(data), 2, simplify = FALSE),
function(x) do.call("segments", as.list(c(t(data[x,])))))
Run Code Online (Sandbox Code Playgroud)
添加铃铛和口哨品尝.
您也可以使用以下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])
})
Run Code Online (Sandbox Code Playgroud)
Jaa*_*aap 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())
Run Code Online (Sandbox Code Playgroud)
这使:
使用数据:
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)
Run Code Online (Sandbox Code Playgroud)
或者,您也可以在不事先添加行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())
Run Code Online (Sandbox Code Playgroud)