gpt4 book ai didi

python - 从绘图色标访问颜色

转载 作者:行者123 更新时间:2023-12-03 16:34:29 38 4
gpt4 key购买 nike

Plotly 有没有办法访问其范围内任何值的颜色图颜色?
我知道我可以从

plotly.colors.PLOTLY_SCALES["Viridis"]
但我无法找到如何访问中间/插值。
Matplotlib 中的等效项显示为 in this question .还有 another question解决了来自 colorlover 的类似问题库,但都没有提供一个很好的解决方案。

最佳答案

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)

关于python - 从绘图色标访问颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62710057/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com