Issue
I really like the additional colormaps like 'dense' or 'ice' from plotly. Nevertheless, I am currently using matplotlib for most of my plots.
Is there a way to use a pyplot colormap in matplotlib plots?
When I take the colormap 'ice' for example, the only thing I get is rgb color as strings with
import plotly.express as px
px.colors.sequential.ice
This just returns
['rgb(3, 5, 18)',
'rgb(25, 25, 51)',
'rgb(44, 42, 87)',
'rgb(58, 60, 125)',
'rgb(62, 83, 160)',
'rgb(62, 109, 178)',
'rgb(72, 134, 187)',
'rgb(89, 159, 196)',
'rgb(114, 184, 205)',
'rgb(149, 207, 216)',
'rgb(192, 229, 232)',
'rgb(234, 252, 253)']
The problem is, I have no idea how to use this in a matplotlib plot. The thing I tried was creating a custom colormap with
my_cmap = matplotlib.colors.ListedColormap(px.colors.sequential.ice, name='my_colormap_name')
but this gave me the following error when used inside a plot:
ValueError: Invalid RGBA argument: 'rgb(3, 5, 18)'
Anyone knows how to convert this properly?
Solution
You have to decode the RGB string:
import plotly.express as px
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
SAMPLES = 20
ice = px.colors.sample_colorscale(px.colors.sequential.ice, SAMPLES)
rgb = [px.colors.unconvert_from_RGB_255(px.colors.unlabel_rgb(c)) for c in ice]
cmap = mcolors.ListedColormap(rgb, name='Ice', N=SAMPLES)
Demo:
import numpy as np
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
plt.imshow(gradient, aspect='auto', cmap=cmap)
plt.show()
Output:
Answered By - Corralien
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.