簡體   English   中英

Python / Matplotlib:帶有contourf的顏色條不尊重自定義cmap的刻度標簽

[英]Python/Matplotlib: colorbar with contourf does not respect the tick labels of custom cmap

我創建了一個自定義cmap和ticklabels來制作一個帶有contourf的plot,但不是所有的ticklabels或所有的colors都被顏色條考慮,但是當我使用imshow時,我得到了我想要的結果。 這是我的代碼。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from matplotlib.colors import BoundaryNorm

x = np.arange(-6,6,0.25)
y = np.arange(-6,6,0.25)
x, y = np.meshgrid(x,y)
z = np.sqrt(x**2+y**2)


newcolors = np.vstack((plt.cm.YlGn(np.linspace(0, 1, 4))[1:,:], plt.cm.Blues(np.linspace(0, 1, 6))))
palette = ListedColormap(newcolors, name='test')

palette.set_over('darkred')
palette.set_under('yellow')

tickslabels=[0.5,1.0,1.5,2.0,4.0,6.0,8.0,10.0,12.0,14.0]
norm=BoundaryNorm(tickslabels, len(tickslabels)-1)


fig1 = plt.figure('imshow')
img=plt.imshow(z, cmap=palette, norm=norm)
plt.colorbar(img, ticks=tickslabels, spacing='proportional', extend='both')
plt.title('imshow')


fig2 = plt.figure('contourf')
img=plt.contourf(x, y, z, cmap=palette, levels=tickslabels, extend='both') #norm=norm)
plt.colorbar(img, ticks=tickslabels, spacing='proportional', extend='both')
plt.title('contourf')

plt.show()

這是使用 imshow 和 contourf 的結果。 Pay attention on colorbar of imshow, the green colors go from 0.5 until 2.0 and the blue colors go from 2.0 until 14.0, this is the result that I want. 然而使用contourf的結果是不一樣的。 我的錯誤是什么? 我忘了設置任何參數?

使用 imshow 繪圖

使用 contourf 繪圖

在繪制輪廓 plot img=plt.contourf(...)時,您必須使用定義的norm=norm 如下使用時,兩個彩條是一樣的

img=plt.contourf(x, y, z, cmap=palette, levels=tickslabels, extend='both', 
                 norm=norm) # <--- pass the norm here

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM