NetworkX:是否为每个节点添加超链接?
问题描述
我开始熟悉networkX了。
我有以下创建网络的脚本:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(1, 3)
G.add_edge(1, 5)
G.add_edge(2, 3)
G.add_edge(3, 4)
G.add_edge(4, 5)
# explicitly set positions
pos = {1: (0, 0), 2: (-1, 0.3), 3: (2, 0.17), 4: (4, 0.255), 5: (5, 0.03)}
options = {
"font_size": 36,
"node_size": 3000,
"node_color": "white",
"edgecolors": "black",
"linewidths": 5,
"width": 5,
}
nx.draw_networkx(G, pos, **options)
# Set margins for the axes so that nodes aren't clipped
ax = plt.gca()
ax.margins(0.20)
plt.axis("off")
plt.show()
此代码生成基本网络。
我想知道谁能告诉我如何编辑此代码,以便我可以向节点添加超链接,这样当我单击某个节点时,它会将我带到一个网页,其中包含有关该节点的更多信息?
(现在我只是想了解玩具网络是否可能做到这一点,这样在本例中,任何URL都可以添加到每个节点,每个节点都应该有一个唯一的URL)。
解决方案
我认为使用networkx和matplotlib无法实现这一点。但您可以使用Bokeh获得一个能够执行您想要的操作的html文件:
import networkx as nx
from bokeh.io import output_file, show
from bokeh.models import (BoxZoomTool, Circle, HoverTool,
MultiLine, Plot, Range1d, ResetTool,
ColumnDataSource, OpenURL, TapTool)
from bokeh.plotting import from_networkx, figure, output_file, show
# Prepare Data
G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(1, 3)
G.add_edge(1, 5)
G.add_edge(2, 3)
G.add_edge(3, 4)
G.add_edge(4, 5)
# explicitly set positions
pos = {1: (0, 0), 2: (-1, 0.3), 3: (2, 0.17), 4: (4, 0.255), 5: (5, 0.03)}
# set urls as node attributes
urls = {
1: "https://stackoverflow.com/questions/69456723/networkx-add-hyperlink-to-each-node",
2: "https://facebook.com",
3: "https://google.com",
4: "Test",
5: "Test"
}
nx.set_node_attributes(G, urls, "URL")
# Show with Bokeh
p = figure(plot_width=400, plot_height=400,
x_range=Range1d(-2, 6), y_range=Range1d(-0.2, 0.5),
tools="tap", title="Click the URL")
# Configure node hover tool and add tools
node_hover_tool = HoverTool(tooltips=[("URL", "@URL")])
p.add_tools(node_hover_tool, BoxZoomTool(), ResetTool())
# Configure tap tool
url = "@URL"
taptool = p.select(type=TapTool)
taptool.callback = OpenURL(url=url)
graph_renderer = from_networkx(G, pos, scale=0.5, center=(0, 0))
graph_renderer.node_renderer.glyph = Circle(size=15, fill_color="white",
line_color = "black", line_width = 1)
graph_renderer.edge_renderer.glyph = MultiLine(line_color="black", line_alpha=1,
line_width=1)
p.renderers.append(graph_renderer)
output_file("interactive_graphs.html")
show(p)
我使用了以下资源: https://docs.bokeh.org/en/latest/docs/user_guide/graph.html和 Turn Bokeh Glyph into a link
相关文章