python?NetworkX庫生成并繪制帶權無向圖
NetworkX是一個非常強大的網絡科學工具,它封裝了圖的數據結構和許多經典圖算法,也內置了許多可視化函數可供調用。
1. 隨機圖生成
最經典的隨機圖當屬我們在上一篇博客《Erdos-Renyi隨機圖的生成方式及其特性》中講到的Erd?s-Rény隨機圖了,我們這里選用其中的Gnp??np形式,調用以下API:
G = nx.erdos_renyi_graph(10, 0.3, seed=1)
這里表示生成10個頂點的圖,且圖的每條邊都以0.3的概率產生。
當然,此時生成的圖不具有權重,我們想在此基礎上均勻隨機初始化[0, 0.4]之間的權重,可以這樣寫:
G = nx.Graph()
for u, v in nx.erdos_renyi_graph(10, 0.3, seed=1).edges():
G.add_edge(u, v, weight=random.uniform(0, 0.4))
2. 2D布局可視化
隨機圖生成好之后,我們就要對其進行可視化了。首先我們需要計算每個節(jié)點在圖中擺放的位置,經典的Fruchterman-Reingold force-directed 算法可以完成這個操作,對應NetworkX中的spring_layout函數:
pos = nx.spring_layout(G, iterations=20) #我們設算法迭代次數為20次
然后就可以分別繪制圖的邊、節(jié)點和節(jié)點標簽了:
nx.draw_networkx_edges(G, pos, edge_color="orange") nx.draw_networkx_nodes(G, pos, node_color="black") nx.draw_networkx_labels(G, pos, font_color="white") plt.show()
繪圖結果如下:

當然,這樣圖的權值是無法體現于圖上的,如果我們需要圖的權值體現于圖上,可以使圖中邊的寬度按照權值大小來設置:
nx.draw_networkx_edges(G,pos, width=[float(d['weight']*10) for (u,v,d) in G.edges(data=True)], edge_color="orange") nx.draw_networkx_nodes(G,pos, node_color="black") nx.draw_networkx_labels(G, pos, font_color="white") plt.show()
此時的繪圖結果如下:

3. 3D布局可視化
如果你覺得2D布局過于扁平,還不夠直觀地體現節(jié)點之間的拓撲關系,那你可以采用如下的代碼對圖進行三維可視化:
# 3d spring layout
pos = nx.spring_layout(G, dim=3, seed=779)
# Extract node and edge positions from the layout
node_xyz = np.array([pos[v] for v in sorted(G)])
edge_xyz = np.array([(pos[u], pos[v]) for u, v in G.edges()])
# Create the 3D figure
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
# Plot the nodes - alpha is scaled by "depth" automatically
ax.scatter(*node_xyz.T, s=100, ec="w")
# Plot the edges
for vizedge in edge_xyz:
ax.plot(*vizedge.T, color="tab:gray")
def _format_axes(ax):
"""Visualization options for the 3D axes."""
# Turn gridlines off
ax.grid(False)
# Suppress tick labels
for dim in (ax.xaxis, ax.yaxis, ax.zaxis):
dim.set_ticks([])
# Set axes labels
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
_format_axes(ax)
fig.tight_layout()
plt.show()
此時的繪圖結果如下:

參考
以上就是python NetworkX庫生成并繪制帶權無向圖的詳細內容,更多關于NetworkX庫繪制帶權無向圖的資料請關注腳本之家其它相關文章!
相關文章
聊聊prod()與cumprod()區(qū)別cumsum()
這篇文章主要介紹了prod()與cumprod()區(qū)別cumsum(),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
解決import tensorflow導致jupyter內核死亡的問題
這篇文章主要介紹了解決import tensorflow導致jupyter內核死亡的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
OpenCV每日函數之BarcodeDetector類條碼檢測器
OpenCV在V4.5.3版本的contrib包中提供了一個barcode::BarcodeDetector類,用于條形碼的識別,這篇文章主要介紹了OpenCV每日函數?BarcodeDetector條碼檢測器,需要的朋友可以參考下2022-06-06

