首页 > 解决方案 > 从 Plotly 色标访问颜色

问题描述

Plotly 中是否有一种方法可以访问其范围内任何值的颜色图颜色?

我知道我可以从

plotly.colors.PLOTLY_SCALES["Viridis"]

但我无法找到如何访问中间/插值。

这个问题中显示了 Matplotlib 中的等价物。还有另一个问题解决了colorlover库中的类似问题,但都没有提供很好的解决方案。

标签: pythonplotly-python

解决方案


Plotly似乎没有这样的方法,所以我写了一个:

import plotly.colors

def get_continuous_color(colorscale, intermed):
    """
    Plotly continuous colorscales assign colors to the range [0, 1]. This function computes the intermediate
    color for any value in that range.

    Plotly doesn't make the colorscales directly accessible in a common format.
    Some are ready to use:
    
        colorscale = plotly.colors.PLOTLY_SCALES["Greens"]

    Others are just swatches that need to be constructed into a colorscale:

        viridis_colors, scale = plotly.colors.convert_colors_to_same_type(plotly.colors.sequential.Viridis)
        colorscale = plotly.colors.make_colorscale(viridis_colors, scale=scale)

    :param colorscale: A plotly continuous colorscale defined with RGB string colors.
    :param intermed: value in the range [0, 1]
    :return: color in rgb string format
    :rtype: str
    """
    if len(colorscale) < 1:
        raise ValueError("colorscale must have at least one color")

    if intermed <= 0 or len(colorscale) == 1:
        return colorscale[0][1]
    if intermed >= 1:
        return colorscale[-1][1]

    for cutoff, color in colorscale:
        if intermed > cutoff:
            low_cutoff, low_color = cutoff, color
        else:
            high_cutoff, high_color = cutoff, color
            break

    # noinspection PyUnboundLocalVariable
    return plotly.colors.find_intermediate_color(
        lowcolor=low_color, highcolor=high_color,
        intermed=((intermed - low_cutoff) / (high_cutoff - low_cutoff)),
        colortype="rgb")

挑战在于内置的 Plotly 色标并没有始终如一地暴露出来。有些已经被定义为色标,另一些只是必须首先转换为色标的色板列表。

Viridis 色阶是用十六进制值定义的,而 Plotly 颜色操作方法不喜欢它,所以最容易从这样的样本构造它:

viridis_colors, _ = plotly.colors.convert_colors_to_same_type(plotly.colors.sequential.Viridis)
colorscale = plotly.colors.make_colorscale(viridis_colors)

get_continuous_color(colorscale, intermed=0.25)
# rgb(58.75, 80.75, 138.25)

推荐阅读