Created
June 6, 2021 04:01
-
-
Save jinhangjiang/8cdafd2211f67e376e9857bf55e1165c to your computer and use it in GitHub Desktop.
Draw subgraphs for a certain node and set a bar of weights to reduce complexity
This file contains 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
def drawnodegraph(graph, nodename, info=False,weightbar=0): | |
# graph will be your networkx graph | |
# nodename will be the node that you want to focus on | |
# the default value for weightbar is 0, if increase the bar, rare relationship will be removed. Assuming no negative weights | |
temp = graph.copy(as_view=False) # make a temporary graph to avoid losing original ones | |
temp.remove_edges_from((e for e, w in nx.get_edge_attributes(temp,'weight').items() if w <= weightbar)) # remove rare relationhsip if weightbar is not 0 | |
nodelist = list(temp.neighbors(n=nodename)) #generate the nodes that have relationship with our target node | |
nodelist.append(nodename) # add the target to the list | |
Sub = temp.subgraph(nodelist) # draw subgraph | |
edges,weights = zip(*nx.get_edge_attributes(Sub,'weight').items()) | |
pos=nx.spring_layout(Sub,k=0.7,seed=42) | |
node_map = {nodename:7000} | |
nodesize=[node_map.get(node, 3500) for node in Sub.nodes()] # enlarge our target node | |
val_map = {nodename:0.5714285714285714} | |
nodecolor = [val_map.get(node, 0.25) for node in Sub.nodes()] # change the color of our target node | |
width = [w*5 for w in weights] # change the edge's width based on the weights of the edges | |
nx.draw_networkx(Sub, | |
pos, | |
cmap=plt.get_cmap('viridis'), | |
with_labels=True, | |
node_size=nodesize, | |
node_color=nodecolor, | |
edgelist=edges, | |
edge_color="black", | |
#edge_cmap=plt.cm.Blues_r, | |
style="solid", | |
font_color='white', | |
font_size=20, | |
width =width) | |
plt.subplots_adjust(left=2, bottom=3.2, right=6, top=6) | |
if info: | |
print("----------------------------------------") | |
print("Density:",nx.classes.function.density(Sub)) | |
print("The information of the graph:",nx.info(Sub)) | |
print("----------------------------------------") | |
return plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment