使用 networkx 在網路中按權重對邊進行著色(Matplotlib)
要在 networkx 中按權重為邊著色,我們可以採取以下步驟 -
- 設定圖形大小並調整子圖之間和周圍的邊距。
- 使用邊、名稱或圖形屬性初始化圖形。
- 將節點新增到當前圖形。
- 將邊新增到當前圖形的節點。
- 迭代給定圖形的邊併為它們設定一些權重。
- 使用 權重為邊顏色繪製當前圖形。
- 要顯示圖形,請使用 show() 方法。
示例
import random as rd import matplotlib.pylab as plt import networkx as nx plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True G = nx.DiGraph() G.add_nodes_from([1, 2, 3, 4]) G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (1, 3)]) for u, v, d in G.edges(data=True): d['weight'] = rd.random() edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items()) nx.draw(G, node_color='b', edge_color=weights, width=2, with_labels=True) plt.show()
輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP