问题描述
我有一个类似于此帖子,但用于其他库 colorlover .我想创建一个色标,然后从该色标中提取特定颜色.
I have a question similar to this post, but it's for a different library, colorlover. I would like to create a colorscale and then pull a specific color from that scale.
例如,
import colorlover as cl
color_scale = cl.scales['3']['div']['Spectral']
color_scale
>['rgb(252,141,89)', 'rgb(255,255,191)', 'rgb(153,213,148)']
然后,我想在比例尺的75%处找到颜色
Then, I'd like to find the color at 75% of the scale with something similar to
color_scale(0.75)
理想情况下将返回该颜色的rgb值.
which would ideally return the rgb value for that color.
我也愿意使用其他任何将返回rgb值或与plotly兼容的颜色格式的软件包.
I'm also open to using any other package that will return a rgb value or a color format that is compatible with plotly.
推荐答案
要从色标中选择一种颜色并以色图方式使用,可以使用 matplotlib颜色图来选择一种颜色,然后将该颜色转换为需要的rgb格式.
To select a single color from a colorscale and use it in plotly, you can use matplotlib colormap to select a color, then convert the color to the rgb format that plotly requires.
例如,
import matplotlib
#Generate a color scale
cmap = matplotlib.cm.get_cmap('Spectral')
#Select the color 75% of the way through the colorscale
rgba = cmap(0.75)
#This produces an rgb format between 0 and 1
print(rgba) # (0.5273356401384084, 0.8106113033448674, 0.6452133794694349, 1.0)
(如果出现错误,则模块'matplotlib'没有属性'cm'
,请尝试以下方法:)
(If that gives an error, module 'matplotlib' has no attribute 'cm'
, try this instead:)
import matplotlib.pyplot as plt
cmap = plt.cm.get_cmap('Spectral')
rgba = cmap(0.75)
print(rgba) # (0.5273356401384084, 0.8106113033448674, 0.6452133794694349, 1.0)
我们现在具有RGB颜色,但是对于绘图来说格式错误.要求格式为'rgb(254,254,190)'
.这可以通过将元组中的上述元素乘以255,然后转换为字符串来实现.
We have an RGB color now, but it's in the wrong format for plotly. Plotly requires the format 'rgb(254, 254, 190)'
. This can be accomplished by multiplying the above elements in the tuple by 255 and then converting to a string.
rgba = tuple(int((255*x)) for x in rgba[0:3])
rgba = 'rgb'+str(line_color)
print(rgba) #'rgb(134, 206, 165)'
rgba
现在是一个字符串,可用于在绘图中选择颜色.
rgba
is now a string that can be used to select a color in plotly.
这篇关于从python中的colorlover中的色标中获取单个颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!