我正在尝试创建一个具有离散等高线水平的填充等高线图,我需要控制它以比较来自不同数据源的值。我认为这应该很容易实现fig.colorbar(c, ax=ax, ticks=my_levels)
。但是,正如您从下面的示例中看到的那样,颜色和值的对齐出现了问题,我无法弄清楚我的代码有什么问题。
这是代码:
# -*- coding: cp1252 -*-
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter
import numpy as np
def plot_discrete(x, y, data, cmax, nclevel=11):
"""Plot filled contour plot and add colorbar with discrete (linear) spacing"""
matplotlib.rcParams.update({'font.size' : 22})
# prepare plot
fig = plt.figure(figsize=(10,7), dpi=150)
fig.suptitle(unicode("Test ÄÖÜßäöü","latin-1"), fontsize=20, fontweight='bold')
ax = fig.add_subplot(1,1,1)
# determine contour levels and set color scale (norm)
clevel = np.linspace(0., cmax, nclevel)
print "clevel = ", clevel
print "cmax, max(data) = ", cmax, np.max(data)
norm = matplotlib.colors.BoundaryNorm(clevel, ncolors=256, clip=False)
# generate the contour plot
c = ax.contourf(x, y, data, level=clevel, norm=norm)
# prep up axis formatting and labelling
ax.set_xlabel('X',{'fontsize':20})
ax.set_ylabel('Y',{'fontsize':20})
ax.xaxis.set_major_formatter(ScalarFormatter())
ax.yaxis.set_major_formatter(ScalarFormatter())
# add the colorbar
fig.colorbar(c, ax=ax, norm=norm, ticks=clevel, boundaries=clevel)
plt.show()
if __name__ == "__main__":
x = np.linspace(0.,10.,20)
y = np.linspace(-10.,10.,21)
data = np.zeros((x.size, y.size))
for i,xx in enumerate(x):
for j,yy in enumerate(y):
data[i,j] = np.sqrt(xx)*yy**2
plot_discrete(y, x, data, 360.)