用于网络的Python Plotly库:如何为不同颜色的节点着色

时间:2016-06-19 23:28:34

标签: python plotly

Python Plotly库启用plot graphs or networks

以下代码(来自此link)是一个函数,它返回一个字典,其中包含要绘制的节点的不同属性:

def scatter_nodes(pos, labels=None, color=None, size=20, opacity=1): # pos is the dict of node positions # labels is a list of labels of len(pos), to be displayed when hovering the mouse over the nodes # color is the color for nodes. When it is set as None the Plotly default color is used # size is the size of the dots representing the nodes #opacity is a value between [0,1] defining the node color opacity L=len(pos) trace = Scatter(x=[], y=[], mode='markers', marker=Marker(size=[])) for k in range(L): trace['x'].append(pos[k][0]) trace['y'].append(pos[k][1]) attrib=dict(name='', text=labels , hoverinfo='text', opacity=opacity) # a dict of Plotly node attributes trace=dict(trace, **attrib)# concatenate the dict trace and attrib trace['marker']['size']=size trace['marker']['color']=color return trace

trace['marker']['color']=color为所有节点指定相同的颜色。

如果我用trace['marker']['color']=random.randint(500)替换此行,它将为每个节点提供随机颜色。

我希望每个节点都有一个字典预定的颜色,节点作为键,颜色作为值。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

简单回答:只需要将color定义为自动使用节点编制索引的颜色列表。