Python: networkx: how to make node auto expand size to fit label

I'm using this bit of code from the deap symbolic regression example and the graph displays fine, but I want the nodes to expand like rounded rectangles to fit the text automatically . (I don't want to just give the node size through trial and error). How should I do it?

# 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()

      

+3


source to share


2 answers


There is no easy way to do this with matplotlib and networkx (of course this is possible with enough code). Graphviz does a great job with shortcuts, and it's easy to write dot files from networkx for processing with Graphviz.
Also have a look at https://github.com/chebee7i/nxpd which can do exactly what you need.



0


source


The node_size argument accepts both scalar and vector values. While a scalar makes all nodes equal in size, a vector helps you specify individual values ​​in a list that will be used for each node. If your node ids are strings, then the following strategy works well enough.

Just change the size argument to a list in networkx.draw_networkx_nodes based on the length of each node id. Select a_base_size appropriately.

networkx.draw_networkx_nodes (graph, pos, node_size = [len (v) * the_base_size for v in graph.nodes ()], node_color = "w")



You can adapt it for the case where you can handle labels as well.

*** However, I'm not sure if a one-to-one match will be preserved while it picks node sizes from a list based on label sizes. Share your results. I have personally used it for string node ids and it works well.

+3


source







All Articles