networkx - 根据边缘属性更改颜色/宽度 - 结果不一致 [英] networkx - change color/width according to edge attributes - inconsistent result

查看:47
本文介绍了networkx - 根据边缘属性更改颜色/宽度 - 结果不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法正确地生成了图表,但通过更多的测试发现以下两行不同的代码结果不一致:

I managed to produce the graph correctly, but with some more testing noted inconsistent result for the following two different line of codes:

colors = [h.edge[i][j]['color'] for (i,j) in h.edges_iter()]
widths = [h.edge[i][j]['width'] for (i,j) in h.edges_iter()]
nx.draw_circular(h, edge_color=colors, width=widths)

这种方法会产生一致的输出,而以下内容会根据边的顺序产生错误的颜色/大小:

This approach results in consistent output, while the following produces wrong color/size per the orders of edges:

colors = list(nx.get_edge_attributes(h,'color').values())
widths = list(nx.get_edge_attributes(h,'width').values())
nx.draw_circular(h, edge_color=colors, width=widths)

但是,在我看来,上面两行都依赖于函数调用来按照边的顺序返回属性.为什么结果不同?

However, it looks to me the above two lines both rely on the function call to return the attributes per the order of edges. Why the different results?

我觉得用h[][][]访问属性有点笨拙;是否可以通过点约定访问它,例如edge.color for edge in h.edges().

It looks a bit clumsy to me to access attributes with h[][][]; is it possible to access it by dot convention, e.g. edge.color for edge in h.edges().

或者我错过了什么?

推荐答案

传递给绘图函数的边的顺序很重要.如果您不指定(使用edges 关键字),您将获得G.edges() 的默认顺序.像这样明确地给出参数是最安全的:

The order of the edges passed to the drawing functions are important. If you don't specify (using the edges keyword) you'll get the default order of G.edges(). It is safest to explicitly give the parameter like this:

import networkx as nx

G = nx.Graph()
G.add_edge(1,2,color='r',weight=2)
G.add_edge(2,3,color='b',weight=4)
G.add_edge(3,4,color='g',weight=6)

pos = nx.circular_layout(G)

edges = G.edges()
colors = [G[u][v]['color'] for u,v in edges]
weights = [G[u][v]['weight'] for u,v in edges]

nx.draw(G, pos, edges=edges, edge_color=colors, width=weights)

这会产生如下输出:

这篇关于networkx - 根据边缘属性更改颜色/宽度 - 结果不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆