简体   繁体   English

如何在Python中绘制不同宽度的networkx图?

[英]How to draw a networkx graph with different widths in Python?

I have been trying to show a graph and I want my edges width to be somewhat related with their weight, meaning tinny when the weight is smaller and larger when the weight is bigger.我一直在尝试显示一个图表,我希望我的边缘宽度与它们的重量有些相关,这意味着当重量更小时很小,而当重量更大时则更大。 It makes all edges with the exactly same width.它使所有边缘的宽度完全相同。 The method amizade is a method that returns the weight. amizade 方法是一个返回权重的方法。 I have imported csv, networkx and mathplotlib.pyplot.我已经导入了 csv、networkx 和 mathplotlib.pyplot。 This is my code so far:到目前为止,这是我的代码:

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()   

Thank you for your help!谢谢您的帮助!

In your code you just need to pass the weights of each edge to width parameter in draw() function.在您的代码中,您只需将每个边的权重传递给draw()函数中的宽度参数。

You can reference the below code.你可以参考下面的代码。 As your code is not reproducible so I have created a random graph由于您的代码不可重现,因此我创建了一个随机图

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))

The graph looks something like this:该图如下所示:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM