Created
May 5, 2015 13:32
-
-
Save darthsuogles/ea9686396ef38a221a8a to your computer and use it in GitHub Desktop.
How to properly plot a graph in networkx and export to json format.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| import networkx as nx | |
| import matplotlib.pyplot as plt | |
| #embedding_coords = nx.spring_layout(G) | |
| embedding_coords = nx.graphviz_layout(G) | |
| #embedding_coords = nx.spectral_layout(G) | |
| #embedding_coords = nx.random_layout(G) | |
| # stored_coords = nx.get_node_aattributes(G, 'embedding') | |
| # for k,v in stored_coords.iteritems(): | |
| # stored_coords[k] = v[:2] | |
| # embedding_coords = stored_coords # coordinates | |
| labels = nx.get_node_attributes(G, 'name') # names for each node | |
| # Set node colors with their betweeness centrality | |
| btwns_c = nx.betweenness_centrality(G) | |
| node_colors = btwns_c.values() | |
| # Node size weighted by edges | |
| edge_weights = nx.get_edge_attributes(G, 'weight') | |
| node_weights = {} | |
| for k,val in edge_weights.iteritems(): | |
| u,v = k | |
| try: # this is a fast way to build dict | |
| node_weights[u] += val | |
| except KeyError: | |
| node_weights[u] = val; pass | |
| for k in G.nodes(): | |
| if k not in node_weights: | |
| node_weights[k] = 1; | |
| # Adjusting the size so that some nodes are not going to take the whole plot | |
| node_sizes = np.sqrt(node_weights.values())/15 | |
| #node_sizes = G.degree().values() | |
| ## Colors: http://matplotlib.org/api/colors_api.html | |
| nx.draw_networkx_nodes(G, embedding_coords, | |
| node_size = node_sizes, | |
| node_color = node_colors, | |
| cmap = plt.cm.Reds) | |
| nx.draw_networkx_edges(G, embedding_coords, alpha = 0.2, | |
| style = 'solid') | |
| # edge_color = edge_weights.values()) | |
| # nx.draw_networkx_labels(G, embedding_coords, labels = labels, alpha = 1.0, | |
| # font_size = 11, font_color = 'g', font_family = 'sans-serif') | |
| plt.axis('off') | |
| plt.title("<title of the graph plot>") | |
| plt.show() | |
| nx.write_dot(G, '<graphviz_saved_file_name>.dot') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment