python - 从 Plotly 色标访问颜色
问题描述
Plotly 中是否有一种方法可以访问其范围内任何值的颜色图颜色?
我知道我可以从
plotly.colors.PLOTLY_SCALES["Viridis"]
但我无法找到如何访问中间/插值。
这个问题中显示了 Matplotlib 中的等价物。还有另一个问题解决了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 - 训练测试拆分后丢弃值
- highcharts - 在 X 轴下显示信息,例如在 Excel 中使用 Highcharts
- sql - MS ACESS 按多个标准对列进行排名
- c - 在 C 中查找素数
- python - 如何使用列表理解遍历对象属性?
- vhdl - 用于读取十六进制并转换为 std_logic_vector 的 Vhdl 代码
- openshift - 部署“分蘖”超过了进度期限
- node.js - 将 jest 与 mongoose 一起使用时,“ReferenceError: You are trying to `import` a file after Jest environment has been torn down”
- python - python中的元组和列表有什么区别,哪个更有效
- java - 使用 Spring Batch 处理一个非常大的数据库表