Add graphviz plot inside matplotlib

Viewed 628

I am visualizing various networks with networkx. Take a look at simple example

    graph = nx.DiGraph()
    graph.add_edge("a", "b")
    graph.add_edge("a", "a")
    nx.draw(graph)
    plt.show()

Unfortunately, networkx plotting does not render self loops. I am aware of other feature rich packages like GraphViz and its implementation pygraphviz. However, such packages do not allow me to customize my plots (like subplots, annotations etc). I can do all of these with networkx as it can plot with matplotlib Axes. Which is very convenient for programmatic manipulations and heavy customizations. Is there way to get network plotting of GraphViz to matplotlib?

I can always embed PNG created by GraphViz into matplotlib plots using imshow. However, its results are horrible with little customization control.

2 Answers

It doesn’t seem like this exists yet. If you want to implement it yourself, there are a few options. If you want to leave the layout to Graphviz and just hand shapes and positions to Matplotlib, two options remain to get the data necessary for rendering:

  1. You use the binaries (like dot) with the -Tjson option, which seems to emit all necessary data for drawing, but I didn’t find documentation for what e.g. the ops are.
  2. You Use Graphviz as a Library. Section 2.3 (Rendering the graph) describes how to access the data.

You then feed this data into the Axes’ Artist (tutorial). Matplotlib also has a tutorial for how to draw paths.

I am not sure why you say networkx does not render self-loops. Isn't this what you are looking for?

import networkx as nx
from matplotlib import pyplot as plt

graph = nx.DiGraph()
graph.add_edges_from([("a", "b"), ("a", "a"), ("b", "b"), ("c", "b"), ("c", "c")])
nx.draw(graph, with_labels=True)
plt.show()

enter image description here

Related