Skip to main content

DOT Language with Graphviz to render in Pyhton

Graphviz gives two main classes Digraph and Graph that create undirected and directed graphs respectively. They can be rendered and displayed directly inside a notebook. The default formate is PDF in the rendering.

See Graphviz Doc.
Graph and Digraph objects have a _repr_mimebundle_() method so they can be rendered and displayed directly inside a Jupyter notebook. For an example, check the examples/graphviz-notebook.ipynb file in the source repository/distribution (or the same notebook in nbviewer).

import graphviz
g = graphviz.Digraph('G', filename='hello.gv')
g.edge('Hello', 'World')
g

Check the generated DOT source code.

print(g.source)
# digraph G {
#	Hello -> World
# }

To use a different output file format you can use the format argument when creating your Graph or Digraph object, or change the format attribute on an existing graph object.
When you need a image in 'png', set format='png' or use attribute as g.format='png'
g.format = 'png'
g.render()
g = graphviz.Digraph('G', filename='hey.gv', format='png')
g.edge('Hey', 'World')
g.render()
The graphs created is rendered and saved as 'png'.

Record-based Nodes
Record-based Nodes are specified by shape values of “record” and “Mrecord”.
Visually, a record is a box, with fields represented by alternating rows of horizontal or vertical subboxes. The Mrecord shape is identical to a record shape, except that the outermost box has rounded corners.

s = graphviz.Digraph('structs', filename='structs_revisited.gv', node_attr={'shape': 'record'})
s = graphviz.Digraph('structs', filename='structs_revisited.gv', node_attr={'shape': 'Mrecord'})

The structure of a record-based node is determined by label parameter with node methode.
s = graphviz.Digraph('structs', filename='structs_revisited.gv', node_attr={'shape': 'Mrecord'})
s.node(name='struct1', label='<f0> left|<f1> middle|<f2> right')
s
'<'string'>', such as '<f0>' in the label assigns a portname to the field and can be combined with the node name to indicate where to attach an edge to the node.

Help for 'node' shows:
graphviz.Digraph.node??
Signature: graphviz.Digraph.node(name, label=None, _attributes=None, **attrs)
Source:   
    def node(self, name, label=None, _attributes=None, **attrs):
        """Create a node.

        Args:
            name: Unique identifier for the node inside the source.
            label: Caption to be displayed (defaults to the node ``name``).
            attrs: Any additional node attributes (must be strings).
        """
        name = self._quote(name)
        attr_list = self._attr_list(label, attrs, _attributes)
        line = self._node % (name, attr_list)
        self.body.append(line)
File:      /usr/local/lib/python3.7/dist-packages/graphviz/dot.py
Type:      function

Comments