如何解决Matplotlib:如何保存交互式networkx图?
我创建了一个具有悬浮功能的加权networkx图,该图显示每个节点的所有连接。保存绘图时,我得到一个静态的PNG图像。我想问一下我是否可以通过悬停功能保存该图,以便与他人共享?
这是我的代码:
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
G = nx.Graph()
G.add_edge("Ted","May",weight=0.5)
G.add_edge("Ted","Ray",weight=1)
G.add_edge("Ted","Chris","Sam",weight=3)
G.add_edge("Ted","April","Ana",weight=0)
G.add_edge("Ana","Ryan",weight=1)
G.add_edge("Ana","Jim",weight=0.5)
G.add_edge("Ana","Ben",weight=1)
for0 = [(u,v) for (u,v,d) in G.edges(data=True) if d["weight"] == 0]
for05 = [(u,d) in G.edges(data=True) if d["weight"] == 0.5]
for1 = [(u,d) in G.edges(data=True) if d["weight"] == 1]
for15 = [(u,d) in G.edges(data=True) if d["weight"] == 1.5]
for3 = [(u,d) in G.edges(data=True) if d["weight"] == 3]
fig,ax = plt.subplots(figsize=(7.2,7.2))
pos = nx.circular_layout(G) # positions for all nodes
names = np.array(["Ted","Ben"])
# nodes
sc = nx.draw_networkx_nodes(G,pos,node_size=700)
# edges
nx.draw_networkx_edges(G,edgelist=for0,width=0)
nx.draw_networkx_edges(G,edgelist=for05,width=0.5)
nx.draw_networkx_edges(G,edgelist=for1,width=1)
nx.draw_networkx_edges(G,edgelist=for15,width=1.5)
nx.draw_networkx_edges(G,edgelist=for3,width=3)
# labels
nx.draw_networkx_labels(G,font_size=20,font_family="sans-serif")
annot = ax.annotate("",xy=(0,0),xytext=(20,20),textcoords="offset points",bbox=dict(boxstyle="round",fc="w"),arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)
def update_annot(ind):
pos = sc.get_offsets()[ind["ind"][0]]
annot.xy = pos
es = [e for e in G[names[ind["ind"]][0]]]
text = "{}".format(es)
annot.set_text(text)
annot.get_bbox_patch().set_alpha(0.4)
return sc
def hover(event):
vis = annot.get_visible()
if event.inaxes == ax:
cont,ind = sc.contains(event)
if cont:
update_annot(ind)
annot.set_visible(True)
fig.canvas.draw_idle()
else:
if vis:
annot.set_visible(False)
fig.canvas.draw_idle()
fig.canvas.mpl_connect("motion_notify_event",hover)
plt.show()
谢谢。
解决方法
如果您不想重写代码,可以将其保存在GEXF中,以便其他人可以在Gephi中打开它:
nx.write_gexf(G,"test.gexf")
或者,如果要将其存储在HTML文件中,则需要使用其他plotly
之类的绘图API,该API支持交互式绘图(see here for some examples)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。