PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, June 26, 2022

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

 June 26, 2022     csv, graph, matplotlib, networkx, python     No comments   

Issue

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. I have imported csv, networkx and 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!


Solution

In your code you just need to pass the weights of each edge to width parameter in draw() function.

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:

enter image description here



Answered By - micro5
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing