Home > Blockchain >  networkx return plot object
networkx return plot object

Time:04-08

The following code plots the graph of network

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')

Since I need to plot multiple graphs for different phases, I need something like

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

so that I can generate subplots. How to return it as plot object so that I can use it as subplots of matplotlib. Also note that there are two plots, one for edge labels and other for graph.

CodePudding user response:

Just pass in the axis using the ax keyword argument.

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

CodePudding user response:

passing the ax worked out for me without any return value

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)
  • Related