networkx return 绘图对象

networkx return plot object

以下代码绘制网络图

def draw(self, layout):
    nx.draw_networkx_edge_labels(self, layout, edge_labels = self.edge_labels())
    nx.draw(self, pos = layout,  labels = self.node_labels(), node_color='yellow',
            node_size = 1.2*10**3, width = 2, node_shape = 'o')

因为我需要为不同的阶段绘制多个图表,所以我需要类似

的东西
def draw(self, layout):
    f, ax = plt.subplots()
    ax = nx.draw_networkx_edge_labels(self, layout, edge_labels = self.edge_labels())
    ax = nx.draw(self, pos = layout,  labels = self.node_labels(), node_color='yellow',
            node_size = 1.2*10**3, width = 2, node_shape = 'o')
    return ax

这样我就可以生成子图了。如何 return 它作为绘图对象,以便我可以将它用作 matplotlib 的子图。另请注意,有两个图,一个用于边缘标签,另一个用于图形。

只需使用 ax 关键字参数传入轴即可。

def draw(self, layout):
    f, ax = plt.subplots()
    nx.draw_networkx_edge_labels(self, layout, edge_labels = self.edge_labels(), ax=ax)
    nx.draw(self, pos = layout,  labels = self.node_labels(), node_color='yellow',
            node_size = 1.2*10**3, width = 2, node_shape = 'o', ax=ax)
    return ax

通过 ax 对我来说没有任何 return 价值

def draw(self, layout, ax):
    nx.draw_networkx_edge_labels(self, layout, edge_labels = self.edge_labels(), ax = ax)
    nx.draw(self, pos = layout,  labels = self.node_labels(), node_color='yellow',
            node_size = 1.2*10**3, width = 2, node_shape = 'o', ax = ax)