networkxdeap

Python: networkx: How to make node size auto-expand to fit the label


I'm using this bit of code from a deap symbolic regression example problem and the graph displays fine but I want the nodes to expand as rounded rectangles to fit the text automatically. (I don't want to just specify the node size through trial and error). How would I do that?

# show tree
import matplotlib.pyplot as plt
import networkx

nodes, edges, labels = gp.graph(bests[0])
graph = networkx.Graph()
graph.add_nodes_from(nodes)
graph.add_edges_from(edges)
pos = networkx.graphviz_layout(graph, prog="dot")

plt.figure(figsize=(7,7))
networkx.draw_networkx_nodes(graph, pos, node_size=900, node_color="w")
networkx.draw_networkx_edges(graph, pos)
networkx.draw_networkx_labels(graph, pos, labels)
plt.axis("off")
plt.show()

Solution

  • There isn't a simple way to do that with matplotlib and networkx (of course it is possible with enough code). Graphviz does a really excellent job with labels and it is easy to write dot format files from networkx to process with Graphviz.
    Also take a look at https://github.com/chebee7i/nxpd which might do exactly what you need.