How to draw a tree more beautifully in networkx

扶醉桌前 提交于 2021-01-21 05:15:40

问题


If I make a tree using networkx and draw it, the nodes overlap. Is there a way to draw it so there is no overlap?

import matplotlib.pyplot as plt
import networkx as nx
T = nx.generators.balanced_tree(2, 5)
nx.draw(T)
plt.show()


回答1:


I am no expert in this, but here is code that uses the pydot library and its graph_viz dependency. These libraries come with Anaconda Python but are not installed by default, so first do this from the command prompt:

conda install pydot

Then here is code adapted from Circular Tree.

import matplotlib.pyplot as plt
import networkx as nx
import pydot
from networkx.drawing.nx_pydot import graphviz_layout

T = nx.balanced_tree(2, 5)

pos = graphviz_layout(T, prog="twopi")
nx.draw(T, pos)
plt.show()

If you adjust the window to make it square, the result is

Or, if you prefer a top-down tree, you could replace the string "twopi" in that code with "dot", and if you make the resulting window wider you get

Also, if you use the string "circo" instead and make the window wider, you get




回答2:


If you want to do this without additional libraries, look at this answer, which shows a way to get a hierarchical tree layout purely in networkx:

https://stackoverflow.com/a/29597209/2966723

I'm planning to add a slightly modified version of this to networkx sometime soon.



来源:https://stackoverflow.com/questions/57512155/how-to-draw-a-tree-more-beautifully-in-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!