如何将连续色标转换为离散色标?

how to convert continuous colorscale into discrete colorscale?

我想使用红色和蓝色两种颜色,但浓度不同,如下所示。 我想将这个连续色标转换为具有 10 种离散颜色的离散色标。

https://plotly.com/python/colorscales/#reversing-a-builtin-color-scale

如果我打印连续色标,它在列表中只有 2 个元素,如下所示。现在我怎样才能得到 10 种不同浓度的红色和蓝色之间的颜色。谢谢

    colors=px.colors.sequential.Bluered_r
    
    print(colors)

    ['rgb(255,0,0)', 'rgb(0,0,255)']

据我所知,plotly 没有明确的功能。 对于 red-blue 比例,基于 np.linspace 的简单实施应该可行。

import numpy as np
def n_discrete_rgb_colors(color1: str, color2: str, n_colors: int) -> list:
    color1_ = [int(i) for i in color1[4:-1].split(",")]
    color2_ = [int(i) for i in color2[4:-1].split(",")]
    colors_ = np.linspace(start = color1_, stop = color2_, num = n_colors)
    colors = [str(f"rgb{int(i[0]),int(i[1]),int(i[2])}") for i in colors_]
    return colors

color1, color2 = ['rgb(255,0,0)', 'rgb(0,0,255)']
# color1, color2 = px.colors.sequential.Bluered_r
n_discrete_rgb_colors(color1, color2, 10)

输出

['rgb(255, 0, 0)',
 'rgb(226, 0, 28)',
 'rgb(198, 0, 56)',
 'rgb(170, 0, 85)',
 'rgb(141, 0, 113)',
 'rgb(113, 0, 141)',
 'rgb(85, 0, 170)',
 'rgb(56, 0, 198)',
 'rgb(28, 0, 226)',
 'rgb(0, 0, 255)']

代码逻辑如下:

  1. 取两个'rgb(x,y,z)'格式的边缘颜色字符串,
  2. 将它们转换成 [x,y,z] 个列表,
  3. 建一个linspace,
  4. return 此 linspace 具有适当的格式
import pandas as pd
import numpy as np
import plotly.express as px

df = pd.DataFrame({c:np.linspace(1,10,100) for c in list("xyc")})

# https://plotly.com/python/colorscales/#constructing-a-discrete-or-discontinuous-color-scale
cmap = [
    (r, c)
    for r, c in zip(
        np.repeat(np.linspace(0, 1, len(px.colors.sequential.RdBu)+1), 2)[1:],
        np.repeat(px.colors.sequential.RdBu,2),
    )
]

px.bar(df, x="x", y="y", color="c", color_continuous_scale=cmap)