matplotlib Networkx绘图-根据边缘的颜色绘制边缘标签

nhjlsmyf  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(234)

是否可以根据标签所属边缘的颜色对标签文本着色?我尝试使用font_color执行此操作,但出现以下错误:ValueError: dict_values(['r', 'g', 'b', 'm', .... 'y']) is not a valid value for color .
我的绘图现在看起来像这样:

colors = nx.get_edge_attributes(graph, 'color').values()
nx.draw_networkx(graph, pos, with_labels=True, connectionstyle='arc3, rad = 0.1', edge_color=colors)
edge_labels_bidirectional = dict([((u, v,), d['initial_balance'])
                    for u, v, d in graph.edges(data=True)])

nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels_bidirectional,
                             label_pos=0.3, font_size=7)
plt.show()

0md85ypi

0md85ypi1#

由于nx.draw_networkx_edge_labels只接受一个字符串作为font_color参数(而不是列表或字典,doc here),因此必须为每条边调用nx.draw_networkx_edge_labels,并使用相应的颜色分别绘制每个标签。
请参见以下代码(网络从此处改编):

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(1, 3)
G.add_edge(1, 5)
G.add_edge(2, 3)
G.add_edge(3, 4)
G.add_edge(4, 5)

pos = {1: (0, 0), 2: (-1, 0.3), 3: (2, 0.17), 4: (4, 0.255), 5: (5, 0.03)}

cmap=plt.cm.viridis(np.linspace(0,1,G.number_of_edges()))
nx.draw_networkx(G, pos,with_labels=True)
nx.draw_networkx_edges(G, pos,edge_color=cmap)
[nx.draw_networkx_edge_labels(G,pos,edge_labels={e:i},font_color=cmap[i]) for i,e in enumerate(G.edges())]

相关问题