简体   繁体   English

Python / Matplotlib:带有contourf的颜色条不尊重自定义cmap的刻度标签

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

I create a custom cmap and ticklabels to make a plot with contourf, but not all the ticklabels nor all the colors are considered by the colorbar, however when I use imshow, I get the result that I want.我创建了一个自定义cmap和ticklabels来制作一个带有contourf的plot,但不是所有的ticklabels或所有的colors都被颜色条考虑,但是当我使用imshow时,我得到了我想要的结果。 This is my code.这是我的代码。

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()

This are the results using imshow and contourf.这是使用 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. 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. However using contourf the result is not the same.然而使用contourf的结果是不一样的。 What is my error?我的错误是什么? I forget set any parameter?我忘了设置任何参数?

使用 imshow 绘图

使用 contourf 绘图

You have to use the defined norm=norm when plotting the contour plot img=plt.contourf(...) .在绘制轮廓 plot img=plt.contourf(...)时,您必须使用定义的norm=norm When used in the following way, both color bars are same如下使用时,两个彩条是一样的

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