use*_*159 7 python graph matplotlib networkx
我在matplotlib尝试networkx和可视化我很困惑因为我不清楚他们如何互相交流?有简单的例子
import matplotlib.pyplot
import networkx as nx
G=nx.path_graph(8)
nx.draw(G)
matplotlib.pyplot.show()
Run Code Online (Sandbox Code Playgroud)
我在哪里告诉pyplot,我想绘制图G?我猜nx.draw使用像matplotlib.pyplot这样的东西.{plot,etc ...}所以,如果我想绘制2个图:
import matplotlib.pyplot
import networkx as nx
G=nx.path_graph(8)
E=nx.path_graph(30)
nx.draw(G)
matplotlib.pyplot.figure()
nx.draw(E)
matplotlib.pyplot.show()
Run Code Online (Sandbox Code Playgroud)
然后......小实验
import networkx as nx
G=nx.path_graph(8)
E=nx.path_graph(30)
nx.draw(G)
import matplotlib.pyplot
matplotlib.pyplot.figure()
nx.draw(E)
import matplotlib.pyplot as plt
plt.show()
Run Code Online (Sandbox Code Playgroud)
请不要因为这个愚蠢的代码而杀了我,我只是想了解 - networkx如何绘制matplotlib的东西,而它甚至还没有导入!
PS:抱歉我的英文.
Phi*_*oud 15
如果要单独绘制图形或创建单个Axes对象并将其传递给它,只需创建两个不同的轴nx.draw.例如:
G = nx.path_graph(8)
E = nx.path_graph(30)
# one plot, both graphs
fig, ax = subplots()
nx.draw(G, ax=ax)
nx.draw(E, ax=ax)
Run Code Online (Sandbox Code Playgroud)
要得到:

如果你想要两个不同的图形对象,则分别创建它们,如下所示:
G = nx.path_graph(8)
E = nx.path_graph(30)
# two separate graphs
fig1 = figure()
ax1 = fig1.add_subplot(111)
nx.draw(G, ax=ax1)
fig2 = figure()
ax2 = fig2.add_subplot(111)
nx.draw(G, ax=ax2)
Run Code Online (Sandbox Code Playgroud)
收益:

最后,如果需要,您可以创建一个子图,如下所示:
G = nx.path_graph(8)
E = nx.path_graph(30)
pos=nx.spring_layout(E,iterations=100)
subplot(121)
nx.draw(E, pos)
subplot(122)
nx.draw(G, pos)
Run Code Online (Sandbox Code Playgroud)
导致:

无论它值多少,当你想在外面创建子图时,看起来像是没有用API 的ax参数,因为有一些调用使它依赖于接口.没有真正深入研究为什么会这样,只是想我会指出它.nx.drawmatplotlibpylabnx.drawgcapylab
源代码nx.draw非常简单:
try:
import matplotlib.pylab as pylab
except ImportError:
raise ImportError("Matplotlib required for draw()")
except RuntimeError:
print("Matplotlib unable to open display")
raise
cf=pylab.gcf()
cf.set_facecolor('w')
if ax is None:
if cf._axstack() is None:
ax=cf.add_axes((0,0,1,1))
else:
ax=cf.gca()
# allow callers to override the hold state by passing hold=True|False
b = pylab.ishold()
h = kwds.pop('hold', None)
if h is not None:
pylab.hold(h)
try:
draw_networkx(G,pos=pos,ax=ax,**kwds)
ax.set_axis_off()
pylab.draw_if_interactive()
except:
pylab.hold(b)
raise
pylab.hold(b)
return
Run Code Online (Sandbox Code Playgroud)
gcf.Axes如果一个对象不存在,则将该对象添加到该图中,否则使用该对象从环境中获取gca.hold上