dominikbraun / graph

A library for creating generic graph data structures and modifying, analyzing, and visualizing them.
https://graph.dominikbraun.io
Apache License 2.0
1.8k stars 94 forks source link

How to draw a graph as beautiful as in README? #81

Closed SilverRainZ closed 1 year ago

SilverRainZ commented 1 year ago

Hi, I am trying to find a package that can draw beautiful directed graphs. It seems the DOT files generated by draw package does not contains any predeinfed attributes. Does the images in README is drawed by DOT? What vertex/edge attributes is it using?

Thank you~

Example code:

g := graph.New(graph.IntHash)

_ = g.AddVertex(1)
_ = g.AddVertex(2)
_ = g.AddVertex(3)
_ = g.AddVertex(4)
_ = g.AddVertex(5)

_ = g.AddEdge(1, 2)
_ = g.AddEdge(1, 4)
_ = g.AddEdge(2, 3)
_ = g.AddEdge(2, 4)
_ = g.AddEdge(2, 5)
_ = g.AddEdge(3, 5)

Corrsponding image in REDAME:

README

The image I got:

output

dominikbraun commented 1 year ago

Hi! You need the attributes colorscheme, color, fillcolor, and if you want, fontname. Additionally, you need the style attribute set to filled.

You can add these attributes using the VertexAttribute option. A graph like in the example could be created as follows (using the Brewer color scheme):

_ = g.AddVertex(1, graph.VertexAttribute("colorscheme", "blues3"), graph.VertexAttribute("style", "filled"), graph.VertexAttribute("color", "2"), graph.VertexAttribute("fillcolor", "1"));
_ = g.AddVertex(2, graph.VertexAttribute("colorscheme", "greens3"), graph.VertexAttribute("style", "filled"), graph.VertexAttribute("color", "2"), graph.VertexAttribute("fillcolor", "1"));
_ = g.AddVertex(3, graph.VertexAttribute("colorscheme", "purples3"), graph.VertexAttribute("style", "filled"), graph.VertexAttribute("color", "2"), graph.VertexAttribute("fillcolor", "1"));
_ = g.AddVertex(4, graph.VertexAttribute("colorscheme", "ylorbr3"), graph.VertexAttribute("style", "filled"), graph.VertexAttribute("color", "2"), graph.VertexAttribute("fillcolor", "1"));
_ = g.AddVertex(5, graph.VertexAttribute("colorscheme", "reds3"), graph.VertexAttribute("style", "filled"), graph.VertexAttribute("color", "2"), graph.VertexAttribute("fillcolor", "1"));

Rendering this will yield the following graph:

Screenshot 2023-02-26 at 12 11 07 PM

To arrange the nodes like in the example, you can use the osage engine for rendering the DOT file - I think this can be done by passing the -Kosage flag to the dot command. The DOT playground yields the following graph:

Screenshot 2023-02-26 at 12 14 47 PM

Now, all you need to do is to add the width and height vertex attributes, and set the fixedheight attribute to true.

SilverRainZ commented 1 year ago

@dominikbraun Thanks for your detailed answer, it is helpful to me. :D