【发布时间】:2020-03-10 08:25:53
【问题描述】:
我想在使用 Networkx 创建的图形的每个节点位置创建饼图。根据this帖子中给出的cmets,我尝试了以下方法。
import pygraphviz as pgv
import networkx as nx
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from pprint import pprint
from collections import OrderedDict
if __name__ == '__main__':
tail = [1, 2, 3]
head = [2, 3, 4]
xpos = [0, 1, 2, 3]
ypos = [0, 0, 0, 0]
xpos_ypos = [(x, y) for x, y in zip(xpos, ypos)]
ed_ls = [(x, y) for x, y in zip(tail, head)]
G = nx.OrderedDiGraph()
G.add_edges_from(ed_ls)
# set node positions
pos = OrderedDict(zip(G.nodes, xpos_ypos))
nx.draw(G, pos=pos, with_labels=True)
nx.set_node_attributes(G, pos, 'pos')
# set node property 1
prop1 = [0.1, 0.2, 0.3, 0.4]
nx.set_node_attributes(G, prop1, 'prop1')
# set node property 2
prop2 = [0.5, 0.6, 0.4, 0.1]
nx.set_node_attributes(G, prop2, 'prop2')
# set node property 3
prop3 = [20, 10, 5, 1]
nx.set_node_attributes(G, prop3, 'prop3')
# set node property 4
prop4 = [24, 256, 2547, 101]
nx.set_node_attributes(G, prop4, 'prop4')
# create pie-chart in nodes
H = nx.nx_agraph.to_agraph(G)
H.node_attr['style'] = 'wedged'
for i in H.nodes():
n = H.get_node(i)
n.attr['prop1'] = # Here, I want to convert this prop1 = [0.1, 0.2, 0.3, 0.4] to colormap and assign colors
plt.show()
有四个属性分配给节点,prop1、prop2、prop3 和 prop4。我想在饼图中创建 4 个相等的分数(类似于 this,但分数相等)并为每个分数着色 基于存储在变量 prop1、prop2、prop3 和 prop4 中的值的分数。
简而言之,不是为每个节点分配单一颜色,而是在这里我有一个饼图,其中分数的数量等于节点属性/属性的数量。为每个属性存储的值将用于为饼图中位于每个节点中心的分数分配颜色。
任何关于如何做到这一点的建议都会很有帮助
【问题讨论】:
-
假设你的节点属性1的值为
[1,1,1,1],一共有4个属性。 IIUC 你想在四分之一的饼图上着色,但是用哪种颜色?你如何确定[0,0,0,1]的颜色是否与[0,0,1,0]不同? -
@warped 非常感谢您的回复。我更愿意根据从所有节点和所有属性的值范围计算出的最大值和最小值来分配色阶。例如,这里的最小值是 0,最大值是 1。因此,[0,0,0,1] 将在第四节被颜色编码为黑色,在其余部分被标记为白色。同样,[0,0,1,0] 将在第三季度用黑色进行颜色编码
标签: python-3.x graph networkx pie-chart pygraphviz