1

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.

For example,

    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)']

Then, I'd like to find the color at 75% of the scale with something similar to

color_scale(0.75)

which would ideally return the rgb value for that color.

I'm also open to using any other package that will return a rgb value or a color format that is compatible with plotly.

1 Answer 1

2

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.

For example,

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)

(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)

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(rgba)
print(rgba) #'rgb(134, 206, 165)'

rgba is now a string that can be used to select a color in plotly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.