Add edge-weights to plot output in networkx

You’ll have to call nx.draw_networkx_edge_labels(), which will allow you to… draw networkX edge labels 🙂 EDIT: full modified source #!/usr/bin/python import networkx as nx import matplotlib.pyplot as plt G=nx.Graph() i=1 G.add_node(i,pos=(i,i)) G.add_node(2,pos=(2,2)) G.add_node(3,pos=(1,0)) G.add_edge(1,2,weight=0.5) G.add_edge(1,3,weight=9.8) pos=nx.get_node_attributes(G,’pos’) nx.draw(G,pos) labels = nx.get_edge_attributes(G,’weight’) nx.draw_networkx_edge_labels(G,pos,edge_labels=labels) plt.savefig(<wherever>)

how to draw communities with networkx

The documentation for networkx.draw_networkx_nodes and networkx.draw_networkx_edges explains how to set the node and edge colors. The patches bounding the communities can be made by finding the positions of the nodes for each community and then drawing a patch (e.g. matplotlib.patches.Circle) that contains all positions (and then some). The hard bit is the graph layout / … Read more

how to draw directed graphs using networkx in python?

Fully fleshed out example with arrows for only the red edges: import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph() G.add_edges_from( [(‘A’, ‘B’), (‘A’, ‘C’), (‘D’, ‘B’), (‘E’, ‘C’), (‘E’, ‘F’), (‘B’, ‘H’), (‘B’, ‘G’), (‘B’, ‘F’), (‘C’, ‘G’)]) val_map = {‘A’: 1.0, ‘D’: 0.5714285714285714, ‘H’: 0.0} values = [val_map.get(node, 0.25) for node … Read more

networkx add_node with specific position

You can use the following approach to set individual node positions and then extract the “pos” dictionary to use when drawing. In [1]: import networkx as nx In [2]: G=nx.Graph() In [3]: G.add_node(1,pos=(1,1)) In [4]: G.add_node(2,pos=(2,2)) In [5]: G.add_edge(1,2) In [6]: pos=nx.get_node_attributes(G,’pos’) In [7]: pos Out[7]: {1: (1, 1), 2: (2, 2)} In [8]: nx.draw(G,pos) … Read more

Using NetworkX with matplotlib.ArtistAnimation

import numpy as np import networkx as nx import matplotlib import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation G = nx.Graph() G.add_edges_from([(0,1),(1,2),(2,0)]) fig = plt.figure(figsize=(8,8)) pos=nx.graphviz_layout(G) nc = np.random.random(3) nodes = nx.draw_networkx_nodes(G,pos,node_color=nc) edges = nx.draw_networkx_edges(G,pos) def update(n): nc = np.random.random(3) nodes.set_array(nc) return nodes, anim = FuncAnimation(fig, update, interval=50, blit=True) nx.draw does not return anything, hence … Read more

Co-occurrence matrix from nested list of words

Another option is to use the constructor csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)]) from scipy.sparse.csr_matrix where data, row_ind and col_ind satisfy the relationship a[row_ind[k], col_ind[k]] = data[k]. The trick is to generate row_ind and col_ind by iterating over the documents and creating a list of tuples (doc_id, word_id). data would simply be a vector of ones … Read more