[英]How to draw a networkx graph with different widths in Python?
我一直在嘗試顯示一個圖表,我希望我的邊緣寬度與它們的重量有些相關,這意味着當重量更小時很小,而當重量更大時則更大。 它使所有邊緣的寬度完全相同。 amizade 方法是一個返回權重的方法。 我已經導入了 csv、networkx 和 mathplotlib.pyplot。 到目前為止,這是我的代碼:
def nx_teste(graf, show_plot=False):
nx_g = nx.Graph()
for i in graf.edges():
# print(i)
# print(i._pessoa_1)
# print(i._pessoa_2)
nx_g.add_edge(i._pessoa_1._pessoa, i._pessoa_2._pessoa,
weight=i._amizade)
print(i._pessoa_1, "->", i._pessoa_2, "=", i._amizade)
if show_plot:
desenho = nx.spring_layout(nx_g)
nx.draw_networkx_nodes(nx_g, desenho, node_size=20,
node_color="#32CD32", edgecolors="#8DEEEE")
nx.draw_networkx_labels(nx_g, desenho, font_size=7)
for f in graf.edges():
nx.draw_networkx_edges(nx_g, desenho, width=f.amizade()**0.01)
nx.draw_networkx_edge_labels(nx_g, desenho, font_size=6)
plt.axis("off")
plt.show()
謝謝您的幫助!
在您的代碼中,您只需將每個邊的權重傳遞給draw()
函數中的寬度參數。
你可以參考下面的代碼。 由於您的代碼不可重現,因此我創建了一個隨機圖
import networkx as nx
import random
G=nx.gnm_random_graph(5,10,seed=42) #creating random graph with 5 nodes and 10 edges
#assigning random weights to each edge
for (u, v) in G.edges():
G.edges[u,v]['weight'] = random.randint(0,5)
#weight of each of the edge
weights = nx.get_edge_attributes(G,'weight').values()
#drawing the graph
nx.draw(G,pos=nx.spring_layout(G),width=list(weights))
該圖如下所示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.