Plot color plots in Matplotlib

王林
Release: 2024-02-14 18:30:04
forward
1015 people have browsed it

在 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
Copy after login

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)']
Copy after login

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')
Copy after login

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

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

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)
Copy after login

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()
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template