Skip to content

Instantly share code, notes, and snippets.

@pacificlion
Last active December 29, 2019 20:43
Show Gist options
  • Select an option

  • Save pacificlion/b1aff2333741d4bd48e454ab0d5f8097 to your computer and use it in GitHub Desktop.

Select an option

Save pacificlion/b1aff2333741d4bd48e454ab0d5f8097 to your computer and use it in GitHub Desktop.
Visualize Network Data
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import networkx as nx
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
plt.figure(figsize=(12, 12))
# 1. Create the graph
# Build your graph
g = nx.from_pandas_edgelist(df,source='SRC',target='DST', edge_attr=None)
# 2. Create a layout for our nodes
layout = nx.spring_layout(g,iterations=50)
# 3. Draw the parts we want
nx.draw_networkx_edges(g, layout, edge_color='#AAAAAA')
answerers = [node for node in g.nodes() if node in df.SRC.unique()]
answerers_size = [value_counts_src[node] for node in g.nodes() if node in df.SRC.unique()]
# for answerers we want the size of nodes to be representative of number of answers they have written
nx.draw_networkx_nodes(g, layout, nodelist=answerers, node_size=[c*40 for c in answerers_size], node_color='lightblue')
questioners = [node for node in g.nodes() if node in df.DST.unique()]
nx.draw_networkx_nodes(g, layout, nodelist=questioners, node_size=100, node_color='#AAAAAA',alpha=0.4)
answerers_dict = dict(zip(answerers, answerers_size))
nx.draw_networkx_labels(g, layout, labels=answerers_dict,font_color='white',font_size=19)
high_degree_questioners = [node for node in g.nodes() if node in df.DST.unique() and value_counts_dst[node] >3]
nx.draw_networkx_nodes(g, layout, nodelist=high_degree_questioners, node_size=100, node_color='#fc8d62', alpha=0.6)
# we do not need axes as there is no need for them
plt.axis('off')
plt.title("Math Overflow Answers vs Questions")
# custom legends
legend_elements = [Line2D([0], [0], marker='o', color='lightblue', label='User with more than 60 answers',
markerfacecolor='lightblue', markersize=15),
Line2D([0], [0], marker='o', color='#AAAAAA', label='User with questions',
markerfacecolor='#AAAAAA', markersize=15),
Line2D([0], [0], marker='o', color='#fc8d62', label='User with more than 3 questions',
markerfacecolor='#fc8d62', markersize=15)
]
# Create the figure and show
plt.legend(handles=legend_elements,loc='upper right')
plt.savefig("Graph.png", format="PNG")
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment