Colormap error when plotting a digraph with networkx

Viewed 72

Plotting undirected graph with a colorbar works, but the same plot for a digraph fails:

def plot(G):
    positions=nx.circular_layout(G)
    nx.get_edge_attributes(G, 'value')
    edges, weights = zip(*nx.get_edge_attributes(G, 'value').items())
    edge_cmap = plt.cm.Spectral.reversed()
    fig, ax = plt.subplots()
    ax = nx.draw_networkx_nodes(G, positions)
    ax = nx.draw_networkx_labels(G, positions)
    ax = nx.draw_networkx_edges(G, positions,
                                edgelist=edges,
                                connectionstyle=f'arc3, rad = 0.25',
                                edge_color = weights,
                                edge_cmap = edge_cmap,
                                edge_vmin=1,
                                edge_vmax=5)
    cbar = fig.colorbar(ax, orientation='vertical')
    return fig

 # toy data
 df = pd.DataFrame({"source": [0, 1, 2],
                   "target": [2, 2, 3],
                   "value": [3, 4, 5]})

Plotting undirected graph works as expected:

G = nx.from_pandas_edgelist(df, 'source', 'target', edge_attr='value')
plot(G)  
plt.show()

Plotting a digrahp returns error:

G = nx.from_pandas_edgelist(df, 'source', 'target', edge_attr='value', 
    create_using=nx.DiGraph)
 plot(G)
plt.show()

Error:

AttributeError: 'list' object has no attribute 'get_array'

1 Answers

With directed graphs, your variable ax=nx.draw_networkx_edges(...) is a list of arrows which isn't a mappable object. However, with undirected graph, ax is a LineCollection which is mappable. See more explanation here. One thing you can do to make the colorbar work with directed graphs is simply add arrows=False in nx.draw_networkx_edges such that ax becomes a LineCollection, which will then in turn make creating the colorbar possible.

Related