thomasp85 / ggraph

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

defining the location of nodes #318

Closed emilioxavier closed 2 years ago

emilioxavier commented 2 years ago

Hi I am updating a collection of R functions that rely on graph and Rgraphviz (both from Bioconductor) along with gridGraphviz. I want to use the ggraph package to provide a better user experience and more options while reducing the reliance on multiple packages.

The goal is to make a graph similar to this one:

Screen Shot 2022-06-20 at 10 31 20 AM

Unfortunately, I cannot figure out how to correctly align the nodes. Specifically, how do I assign a specific location within the plot area to a specific node?

Is defining the position of nodes possible with ggraph? Any help would be greatly appreciated. Even if, unfortunately, it is not possible.

Thank you Emilio

pjt222 commented 2 years ago

Hi @emilioxavier, I recently had a comparable issue with manualy defining node positions and followed a suggestion from https://stackoverflow.com/questions/5364264/how-to-control-the-igraph-plot-layout-with-fixed-positions

The following adaption worked for me.

library(igraph)
library(ggplot2)
library(ggraph)

fixed_coord_example <- function() {
  nodes <- c("a", "b", "c", "d")
  x <- c(0, .6, 1, 1)
  y <- c(0, 0, 1, -1)
  from <- c("a", "b", "b")
  to <- c("b", "c", "d")
  NodeList <- data.frame(nodes, x, y)
  EdgeList <- data.frame(from, to)
  a <- graph_from_data_frame(vertices = NodeList, d = EdgeList, directed = TRUE)
  # plot(a)
  ggraph(a, layout = "manual", x = x, y = y) +
    geom_edge_fan(strength = 1, alpha = .5) +
    geom_node_point(alpha = .5) +
    geom_node_label(aes(label = nodes)) +
    xlim(c(0, 1)) +
    ylim(c(-1, 1))
}
fixed_coord_example()

Created on 2022-06-27 by the reprex package (v2.0.1)

Every node has an x and y position. Depending on your workflow, you could define them before creating a graph object (as in the example above) or afterwards. To change node and/or edge attributes of a graph object you should be aware of the activate function:

https://tidygraph.data-imaginist.com/reference/activate.html

Best regards Philipp

emilioxavier commented 2 years ago

Hi Philipp (aka @pjt222) Thank you sooooo much! This looks awesome! I cannot wait to try it!

All the best, stay hopeful Emilio