Home  >  Article  >  Backend Development  >  Plot color plots in Matplotlib

Plot color plots in Matplotlib

王林
王林forward
2024-02-14 18:30:04980browse

在 Matplotlib 中绘制颜色图

Question content

I really like the additional colormaps in plotly, such as "Dense" or "Ice". Nonetheless, I currently use matplotlib for most of my plotting.

Is there a way to use pyplot colormaps with matplotlib figures?

When I take the colormap "ice" as an example, the only results I get are rgb colors as strings

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 don't know how to use it in matplotlib plots. What I tried was creating a custom colormap

my_cmap = matplotlib.colors.listedcolormap(px.colors.sequential.ice, name='my_colormap_name')

But this gives me the following error when used in a plot:

ValueError: Invalid RGBA argument: 'rgb(3, 5, 18)'

Does anyone know how to convert it correctly?


Correct Answer


You must 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:

The above is the detailed content of Plot color plots in Matplotlib. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete