如何在Python中绘制不同宽度的networkx图?
How to draw a networkx graph with different widths in Python?
我一直在尝试显示一个图表,我希望我的边缘宽度与它们的重量有些相关,这意味着当重量较小时细小,当重量较大时较大。它使所有边缘具有完全相同的宽度。方法 amizade 是 returns 权重的方法。我导入了 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))
图表看起来像这样:
我一直在尝试显示一个图表,我希望我的边缘宽度与它们的重量有些相关,这意味着当重量较小时细小,当重量较大时较大。它使所有边缘具有完全相同的宽度。方法 amizade 是 returns 权重的方法。我导入了 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))
图表看起来像这样: