Function to draw generic (di)graphs #552
Replies: 2 comments 5 replies
-
This is really cool thanks for sharing! We've been thinking of creating an examples or gallery repsitory that can be contributed to but we just don't have the time atm. That said it might be worth contributing this to fletcher, or even turning this into its own package. It would be nice to take the current tree lib and combine it with fletcher. It would also be nice to bring the arrows/lines from fletcher to cetz. |
Beta Was this translation helpful? Give feedback.
-
Feel free to open a PR for adding this to the gallery. I am also open to include it into cetz itself (/src/lib/digraph), but I guess a separate package would be better? Looks very good! |
Beta Was this translation helpful? Give feedback.
-
I've been using Typst for my computer science homework in university, and I ended up needing to draw several graphs (the discrete math kind). So I looked into CeTZ.
I came up with a function to take a list of nodes and a list of edges and draw such a graph.
The function (and its helper) are pretty long, but that's because they're both as generic and customizable as possible.
The
radiallayout()
function just lays out generic objects along a circle.It's intended to be used inside of an existing
cetz.canvas({ ... })
.The
radialgraph()
function draws the graphs completely.It supports simple graphs, simple directed graphs, and multigraphs (both directed or undirected).
However, it won't draw loops, i.e. edges starting and ending at the same node.
I'd also be happy to generate some additional graphs for the gallery, but I don't know if they'd be wanted because the gallery has mostly short code snippets, and a 180-line function would look pretty intimidating for prospective users.
Examples
The code used to generate each graph is in the dropdown below each image.
Each code sample uses the
radialgraph()
function which is listed after the examples.Code
#radialgraph( nodes: ("A", "B", "C", "D"), edges: ( ("A", "B"), ("B", "C"), ("C", "D"), ("D", "A"), ("A", "C"), ), radius: 1.8cm, )
Code
Code
Code
#radialgraph( nodes: ("A", "B", "C", "D", "E"), edges: ( ("A", ("B", "C", "D", "E")), ("B", ("C", "D", "E")), ("C", ("D", "E")), ("D", "E"), ), radius: 2cm )
Code
#radialgraph( nodes: range(0, 5 + 1).map(str), edges: ( ("2", ("1", "0", "5")), ("3", ("1", "0", "5")), ("4", ("1", "0", "5")), ), radius: 2.5cm, radial-start: 0deg, )
Graph layout functions
Below are the functions which perform the actual graph drawing.
Yes, they are very long. However, much of the length is just from comments.
The
radialgraph()
function is a little complicated, but if you don't care to understand how it works, you can use it very easily like in the examples above.radiallayout()
radialgraph()
Beta Was this translation helpful? Give feedback.
All reactions