【问题标题】:Apply color to specific node networkx将颜色应用于特定节点 networkx
【发布时间】:2017-09-02 01:33:30
【问题描述】:

我想通过节点属性的值为我的图表中的节点着色,并且对于属性的特定值,我想应用渐变。这与我看到的(许多!)其他响应不同,它们旨在为图中的所有节点从matplotlib cmap(例如cmap = plt.get_cmap('Greens'))添加颜色。我想将一种颜色应用于一种类型的节点,并将颜色映射应用于另一种类型的节点。

这是我到目前为止所尝试的。我认为这是失败的,因为我正在尝试将字符串(例如'yellow')和rgba值(例如cmap(dict_1[node]))添加到color_map,然后我将其用于nx.draw()node_color参数。

import networkx as nx
import matplotlib.pyplot as plt

color_map = []
cmap = plt.get_cmap('Greens')

for node in g:
    if node in list_1:
        color_map.append('yellow')
    elif node in list_2:
        rgba = cmap(dict_1[node])
        color_map.append(rgba*-1)

nx.draw(g, node_color = color_map, node_size = 75)

color_map 方法在我只按名称向color_map 添加颜色时工作得很好,但不是以当前形式。

【问题讨论】:

    标签: python matplotlib networkx


    【解决方案1】:

    好吧,我找到了解决方案。

    我找到了帮助 hereherehere

    我更改了 elif 语句以使用我修改的新函数:convert_to_hex,并将输出放入 color_map - 它按预期工作。

    def convert_to_hex(rgba_color) :
        red = int(rgba_color[0]*255)
        green = int(rgba_color[1]*255)
        blue = int(rgba_color[2]*255)
        return '#%02x%02x%02x' % (red, green, blue)
    
    import networkx as nx
    import matplotlib.pyplot as plt
    
    color_map = []
    cmap = plt.get_cmap('Greens')
    
    for node in g:
        if node in list_1:
            color_map.append('yellow')
        elif node in list_2:
            rgba = cmap(dict_1[node])
            color_map.append(convert_to_hex(rgba))
    
    
    nx.draw(g, node_color = color_map, node_size = 75)
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      相关资源
      最近更新 更多