简体   繁体   English

添加边缘权重以在 networkx 中绘制输出

[英]Add edge-weights to plot output in networkx

I am doing some graph theory in python using the networkx package.我正在使用 networkx 包在 python 中做一些图论。 I would like to add the weights of the edges of my graph to the plot output.我想将图表边缘的权重添加到绘图输出中。 How can I do this?我怎样才能做到这一点?

For example How would I modify the following code to get the desired output?例如,我将如何修改以下代码以获得所需的输出?

import networkx as nx
import matplotlib.pyplot as plt

G=nx.Graph()
i=1
G.add_node(i,pos=(i,i))
G.add_node(2,pos=(2,2))
G.add_node(3,pos=(1,0))
G.add_edge(1,2,weight=0.5)
G.add_edge(1,3,weight=9.8)
pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)
plt.savefig("path.png")

I would like 0.5 and 9.8 to appear on the edges to which they refer in the graph.我希望 0.5 和 9.8 出现在它们在图中所指的边缘上。

You'll have to call nx.draw_networkx_edge_labels() , which will allow you to... draw networkX edge labels :)您必须调用nx.draw_networkx_edge_labels() ,这将允许您...绘制 networkX 边缘标签 :)

EDIT: full modified source编辑:完全修改源

#!/usr/bin/python
import networkx as nx
import matplotlib.pyplot as plt

G=nx.Graph()
i=1
G.add_node(i,pos=(i,i))
G.add_node(2,pos=(2,2))
G.add_node(3,pos=(1,0))
G.add_edge(1,2,weight=0.5)
G.add_edge(1,3,weight=9.8)
pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
plt.savefig(<wherever>)

I like to do it like this:我喜欢这样做:

import matplotlib.pyplot as plt
pos=nx.spring_layout(G) # pos = nx.nx_agraph.graphviz_layout(G)
nx.draw_networkx(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)

how to make a program in python that will generate the following:如何在 python 中制作一个程序,它将生成以下内容:

  1. generate ladder graph in python 2.calculate its edge to edge distance在python 2中生成梯形图。计算其边缘到边缘的距离
  2. also how to made a program that will calculate the degree and add the total degree of all same degree nodes还如何制作一个程序来计算度数并添加所有相同度数节点的总度数

nadeem awan email address: silky.awan@gmail.com nadeem awan 电子邮件地址:silky.awan@gmail.com

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

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