简体   繁体   中英

Python Plotly library for networks: how to color nodes with different colors

The Python Plotly library enables to plot graphs or networks .

The following code (from this link ) is a function that returns a dictionary with different attributes of the nodes to be drawn:

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

The line trace['marker']['color']=color assigns the same color to all nodes.

If I replace this line by trace['marker']['color']=random.randint(500) , it will give a random color to each node.

I would like for each node to have a color predetermined by dictionary with nodes as keys and colors as values.

How might I proceed?

简单的答案:只需要将color定义为随节点自动索引的颜色列表即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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