thomasp85 / ggraph

Grammar of Graph Graphics
https://ggraph.data-imaginist.com
Other
1.08k stars 116 forks source link

link edge length to aesthetic #309

Closed hkaspersen closed 2 years ago

hkaspersen commented 2 years ago

Is it possible to link the edge lengths to a value in the graph data? I.e. I want to create a network where the nodes are placed based on the numerical value added in the network data.

Some dummy data:

data <- data.frame(
  from = c("A","B","C"),
  to = c("B","C","A"),
  value = c(10, 1, 20)
)

vertices <- data.frame(name = c("A", "B", "C"))

testdata <- igraph::graph_from_data_frame(data, vertices = vertices)

ggraph(testdata, layout = "kk") +
  geom_edge_fan() +
  geom_node_text(aes(label = name),
                 color = "red")

This produces the following plot: Rplot01

Is it possible to make it scale the edge lengths based on the value column in the data so that C appear closer to B, and A further away from C?

schochastics commented 2 years ago

You can use the graphlayouts package for this.

library(ggraph)
library(graphlayouts)
data <- data.frame(
  from = c("A","B","C"),
  to = c("B","C","A"),
  value = c(10, 1, 20)
)

vertices <- data.frame(name = c("A", "B", "C"))

testdata <- igraph::graph_from_data_frame(data, vertices = vertices)

ggraph(testdata, layout = "stress",weight = 1/value) +
  geom_edge_fan() +
  geom_node_text(aes(label = name),
                 color = "red")+
  coord_equal()

Created on 2022-05-03 by the reprex package (v2.0.1)