首頁  >  文章  >  後端開發  >  在 Matplotlib 中繪製顏色圖

在 Matplotlib 中繪製顏色圖

王林
王林轉載
2024-02-14 18:30:04980瀏覽

在 Matplotlib 中绘制颜色图

問題內容

我真的很喜歡plotly 中的附加色彩圖,例如「密集」或「冰」。儘管如此,我目前的大部分繪圖都使用 matplotlib。

有沒有辦法在 matplotlib 圖中使用 pyplot 色彩圖?

當我以顏色圖「ice」為例時,我得到的唯一結果是 rgb 顏色作為字串

import plotly.express as px

px.colors.sequential.ice

這只是回傳

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

問題是,我不知道如何在 matplotlib 圖中使用它。我嘗試的事情是創建自訂顏色圖

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

但是在繪圖中使用時這給了我以下錯誤:

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

有人知道如何正確轉換它嗎?


正確答案


您必須解碼 rgb 字串:

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)

演示:

import numpy as np

gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
plt.imshow(gradient, aspect='auto', cmap=cmap)
plt.show()

輸出:

以上是在 Matplotlib 中繪製顏色圖的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除