首页 > 解决方案 > Python / Matplotlib:带有contourf的颜色条不尊重自定义cmap的刻度标签

问题描述

我创建了一个自定义 cmap 和 ticklabels 以使用 contourf 绘制绘图,但并不是所有的 ticklabels 或所有颜色都被颜色条考虑,但是当我使用 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 的结果。注意imshow的colorbar,绿色从0.5到2.0,蓝色从2.0到14.0,这就是我想要的结果。然而使用contourf的结果是不一样的。我的错误是什么?我忘了设置任何参数?

使用 imshow 绘图

使用 contourf 绘图

标签: pythonmatplotlib

解决方案


norm=norm绘制等高线图时必须使用定义img=plt.contourf(...)。如下使用时,两个彩条是一样的

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

在此处输入图像描述


推荐阅读