我正在尝试创建一个交互式网络分析图。我无法渲染一个交互式版本,告诉我每个节点的连接。我希望能够单击一个节点并突出显示连接。
import networkx as nx
G = nx.Graph()
for col in df_unique.columns:
for row in df_unique[col]:
for word1 in row.split():
if word1.isalpha():
for word2 in row.split():
if word2.isalpha() and word1 != word2:
G.add_edge(word1, word2)
for node in list(G.nodes()):
if not node.isalpha():
G.remove_node(node)
node_color_map = []
for node in G.nodes():
if len(list(G.neighbors(node))) >= 10:
node_color_map.append("#F5AC27")
elif len(list(G.neighbors(node))) >= 5:
node_color_map.append("#F2888B")
elif len(list(G.neighbors(node))) ==1:
node_color_map.append("silver")
else:
node_color_map.append("#90EE90")
import matplotlib.patches as mpatches
gold_patch = mpatches.Patch(color="#F5AC27", label='10 or more connections')
pink_patch = mpatches.Patch(color="#F2888B", label = '5-9 connections')
green_patch = mpatches.Patch(color="#90EE90", label = '2-4 connections')
silver_patch = mpatches.Patch(color="silver", label = 'Only 1 connection')
plt.figure(figsize=(24,24))
plt.title('Network Analysis of Words in Chinese Restaurant Names')
plt.legend(handles=[gold_patch, pink_patch, green_patch, silver_patch])
# draw the graph
pos = nx.spring_layout(G, k=0.7, iterations=28)
nx.draw(G, with_labels=True, font_weight='bold',
pos=nx.spring_layout(G, k=0.4, iterations=20),
node_color =node_color_map,
node_size=[G.degree(node)*100 for node in G],
font_size=10,
font_color='black',
font_family='sans-serif',
alpha=0.73)
from pyvis.network import Network
# create network
net = Network(height="750px", width="100%", bgcolor="#222222", font_color="white")
# add nodes
for idx, node in enumerate(G.nodes()):
net.add_node(node, color=node_color_map[idx])
# add edges
for edge in G.edges():
source, target = edge[0], edge[1]
net.add_edge(source, target)
net.show("network.html")
AttributeError: 'NoneType' object has no attribute 'render'
I tried rendering the Network in the Notebook. The code runs but i dont see any visualization.
如果您使用笔记本,请更新以下行
net = Network(height="750px", width="100%", bgcolor="#222222", font_color="white", notebook=True, cdn_resources='in_line')
#save the HTML instead of show the html
net.save_graph("network.html")
from IPython.display import HTML
HTML(filename="network.html")