是通过使用一些可视化库和工具来实现的。下面是一种常用的方法:
import networkx as nx
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建一个2D图形
G = nx.Graph()
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1)])
# 将图形转换为3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制节点
pos = nx.spring_layout(G, dim=3)
for node in G.nodes():
ax.scatter(pos[node][0], pos[node][1], pos[node][2], c='r', marker='o')
# 绘制边
for edge in G.edges():
ax.plot([pos[edge[0]][0], pos[edge[1]][0]],
[pos[edge[0]][1], pos[edge[1]][1]],
[pos[edge[0]][2], pos[edge[1]][2]])
# 设置坐标轴和标题
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D Interactive Graph')
# 显示图形
plt.show()
import networkx as nx
from bokeh.plotting import figure, show
from bokeh.io import output_notebook
from bokeh.models import HoverTool
# 创建一个2D图形
G = nx.Graph()
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1)])
# 创建一个Bokeh图形对象
plot = figure(title='3D Interactive Graph')
# 绘制节点
pos = nx.spring_layout(G, dim=3)
node_source = ColumnDataSource(dict(x=[], y=[], z=[]))
plot.circle('x', 'y', 'z', size=10, color='red', alpha=0.7, source=node_source)
node_source.data = dict(x=[pos[node][0] for node in G.nodes()],
y=[pos[node][1] for node in G.nodes()],
z=[pos[node][2] for node in G.nodes()])
# 绘制边
edge_source = ColumnDataSource(dict(xs=[], ys=[], zs=[]))
plot.multi_line('xs', 'ys', 'zs', line_color='gray', alpha=0.5, source=edge_source)
edge_source.data = dict(xs=[[pos[edge[0]][0], pos[edge[1]][0]] for edge in G.edges()],
ys=[[pos[edge[0]][1], pos[edge[1]][1]] for edge in G.edges()],
zs=[[pos[edge[0]][2], pos[edge[1]][2]] for edge in G.edges()])
# 添加悬停工具
hover = HoverTool(tooltips=[('Node', '@index')], renderers=[circle_renderer])
plot.add_tools(hover)
# 在Notebook中显示图形
output_notebook()
show(plot)
这些方法可以将networkx 2D图形转换为3D交互式图形,从而实现更直观、更具交互性的数据可视化。这对于展示复杂的网络结构、社交网络、科学研究等领域非常有用。
领取专属 10元无门槛券
手把手带您无忧上云