如何根据存储在字典中的 rgb 值在和弦图中使用颜色

How to use colors in a Chord diagram based on rgb values stored in a dict

我正在尝试根据存储在字典中的 rgb 值更改弦图中圆弧的颜色。我正在使用全息视图。以下代码创建一个和弦图并使用 'Category20' 调色板组;

    import pandas as pd
    import numpy as np
    from holoviews import opts, dim
    import holoviews as hv
    hv.extension('bokeh')
    hv.output(size=200)

    my_dict = {'khaki': {'khaki': 21, 'mediumslateblue': 22, 'lightgreen': 15, 'lightcoral': 13}, 'mediumslateblue': {'khaki': 23, 'mediumslateblue': 13, 'lightgreen': 4, 'lightcoral': 21}, 'lightgreen': {'khaki': 23, 'mediumslateblue': 16, 'lightgreen': 10, 'lightcoral': 9}, 'lightcoral': {'khaki': 4, 'mediumslateblue': 10, 'lightgreen': 29, 'lightcoral': 9}}
    color_dict = {'Color': {0: '(252, 255, 104)', 1: '(104, 107, 255)', 2: '(104, 255, 119)', 3: '(255, 104, 129)'}, 'ColorName': {0: 'khaki', 1: 'mediumslateblue', 2: 'lightgreen', 3: 'lightcoral'}}

    df = pd.DataFrame(my_dict)
    df_colors = pd.DataFrame(color_dict)
    print(df)
    print(df_colors)
    data = hv.Dataset((list(df.columns), list(df.index), df),['source', 'target'], 'value').dframe()

    chord=hv.Chord(data)

    chord.opts(
        opts.Chord(cmap='Category20', edge_cmap='Category20', edge_color=dim('source').str(), 
                   label_index='index', node_color=dim('index').str()))

但是,我想使用 'color_dict' 词典中定义的颜色。如果我将这本字典转换为数据框,它看起来像这样;

             Color        ColorName
0  (252, 255, 104)            khaki
1  (104, 107, 255)  mediumslateblue
2  (104, 255, 119)       lightgreen
3  (255, 104, 129)       lightcoral

我用来创建弦图的数据框使用 'ColorName' 作为列名和索引标签;

                       khaki  mediumslateblue  lightgreen  lightcoral
    khaki               21               23          23           4
    mediumslateblue     22               13          16          10
    lightgreen          15                4          10          29
    lightcoral          13               21           9           9


是否可以使用这个词典来定义弦图中圆弧的颜色?

太棒了,你使用和弦图。 docs 说吧:

You can make your own custom colormaps by providing a list of hex colors:
img.options(cmap=['#0000ff', '#8888ff', '#ffffff', '#ff8888', '#ff0000'], colorbar=True, width=400)

将您的字典转换为十六进制颜色列表:

import webcolors

color_dict = {'Color': {0: (252, 255, 104), 1: (104, 107, 255), 2: (104, 255, 119), 3: (255, 104, 129)}}

color_lst = [rgb for item in color_dict.values() for rgb in item.values()]
color_lst = [webcolors.rgb_to_hex(rgb) for rgb in color_lst]

然后设置cmap=color_lst:

chord.opts(opts.Chord(cmap=color_lst, edge_cmap='Category20', edge_color=dim('source').str(), label_index='index', node_color=dim('index').str()))