networkx和matplotlib之间的交互

8

我正在尝试使用networkx和matplotlib进行可视化,但是我很困惑,因为我不太清楚它们之间如何交互?这里有一个简单的例子。

import matplotlib.pyplot
import networkx as nx
G=nx.path_graph(8)
nx.draw(G)
matplotlib.pyplot.show()

我该在哪里告诉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()

然后...小实验。
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()

请不要因这段愚蠢的代码而杀了我,我只是在尝试理解 - networkx如何在还没有导入matplotlib的情况下绘制图形!
附注:抱歉我的英语。
1个回答

17

如果您想单独绘制图形,请创建两个不同的轴,或者创建一个Axes对象并将其传递给nx.draw。例如:

如果要分别绘制两个图形,请创建两个不同的轴;如果要在同一张图中绘制两个图形,请创建一个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)

获取:

输入图像描述

如果您想要两个不同的图形对象,则需要分别创建它们,如下所示:

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)

产出:

enter image description here enter image description here

最后,如果你愿意的话,你可以创建一个子图,就像这样:

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)

导致:

enter image description here

无论价值如何,看起来在使用matplotlib的API创建pylab之外的子图时,nx.draw中的ax参数是无用的,因为nx.draw有一些对gca的调用,使其依赖于pylab接口。我没有深入研究这个问题,只是想指出这一点。

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
  1. 使用gcf从环境中捕获一个图形。
  2. 然后,如果不存在,则向该图添加一个Axes对象,否则使用gca从环境中获取它。
  3. 将绘图面颜色设置为白色。
  4. 打开hold
  5. 使用内部函数进行绘制。
  6. 关闭坐标轴。
  7. 最后,如果处于交互模式,则绘制并重新引发任何捕获到的异常。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接