这是那些想要不能使用 contourf 或出于其他原因需要 fill_between 的解决方案(如在这种情况下使用不规则的网格数据)。
import numpy as np
import matplotlib.pyplot as plt
from random import randint, sample
import matplotlib.colorbar as cbar
# from Numeric import asarray
%matplotlib inline
# The edges of 2d grid
# Some x column has varying rows of y (but always the same number of rows)
# z array that corresponds a value in each xy cell
xedges = np.sort(sample(range(1, 9), 6))
yedges = np.array([np.sort(sample(range(1, 9), 6)) for i in range(5)])
z = np.random.random((5,5))
f, ax = plt.subplots(1, sharex=True, figsize=(8,8))
f.subplots_adjust(hspace=0)
ax.set_ylabel(r'y')
ax.set_xlabel(r'x')
ax.set_ylim(0,10)
ax.set_xlim(0,10)
c = ['r','g','b','y','m']
normal = plt.Normalize(z.min(), z.max())
cmap = plt.cm.jet(normal(z))
# plot showing bins, coloured arbitrarily.
# I want each cell coloured according to z.
for i in range(len(xedges)-1):
for j in range(len(yedges)):
ax.vlines(xedges[i],yedges[i][j],yedges[i][j+1],linestyle='-')
ax.hlines(yedges[i][j],xedges[i],xedges[i+1],linestyle='-')
ax.vlines(xedges[i+1],yedges[i][j],yedges[i][j+1],linestyle='-')
ax.hlines(yedges[i][j+1],xedges[i],xedges[i+1],linestyle='-')
ax.fill_between([xedges[i],xedges[i+1]],yedges[i][j],yedges[i][j+1],facecolor=cmap[i][j][:])
cax, _ = cbar.make_axes(ax)
cb2 = cbar.ColorbarBase(cax, cmap=plt.cm.jet,norm=normal)
这给
