Draw lines between all the coordinates on the graph.

I have the following framework:

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

I can build these coordinates using the ggplot function and draw a line between these coordinates:

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

Still no problem. But instead of a single line, although the coordinates, I want the line to be drawn between all the coordinates. Creating a kind of web between all coordinates. Is this possible in the ggplot2 package?

+5
source share
2 answers

If you want to do this in ggplot2 , you can use geom_segment for this. But before you can make such a plot, you need to create a data frame that links each observation with other observations. You can approach it as follows:

 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()) 

which gives:

enter image description here


Used data:

 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) 

Alternatively, you can also add the line identifier on the fly without doing this in advance:

 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()) 
+13
source

Using base build:

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

enter image description here

Add bells and whistles to taste.

You can also use the FUN argument in 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]) }) 
+14
source

Source: https://habr.com/ru/post/1245091/


All Articles