笔记
单击此处 下载完整的示例代码
pcolormesh #
axes.Axes.pcolormesh
允许您生成 2D 图像样式的图。请注意,它比类似的要快pcolor
。
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
import numpy as np
基本 pcolormesh #
我们通常通过定义四边形的边和四边形的值来指定 pcolormesh。请注意,这里x和y在各自的维度中都比 Z 多一个元素。
np.random.seed(19680801)
Z = np.random.rand(6, 10)
x = np.arange(-0.5, 10, 1) # len = 11
y = np.arange(4.5, 11, 1) # len = 7
fig, ax = plt.subplots()
ax.pcolormesh(x, y, Z)
<matplotlib.collections.QuadMesh object at 0x7f2d00aaeef0>
非直线 pcolormesh #
请注意,我们还可以为X和Y指定矩阵并具有非直线四边形。
<matplotlib.collections.QuadMesh object at 0x7f2d00c610f0>
居中坐标#
通常,用户希望将大小与Z相同的X和Y传递给
。如果通过(默认设置为(默认值:)) ,这也是允许的。在 Matplotlib 3.3 之前,
会删除Z的最后一列和最后一行;虽然出于向后兼容的目的仍然允许这样做,但会引发 DeprecationWarning。如果这确实是您想要的,那么只需手动删除 Z 的最后一行和最后一列:axes.Axes.pcolormesh
shading='auto'
rcParams["pcolor.shading"]
'auto'
shading='flat'
x = np.arange(10) # len = 10
y = np.arange(6) # len = 6
X, Y = np.meshgrid(x, y)
fig, axs = plt.subplots(2, 1, sharex=True, sharey=True)
axs[0].pcolormesh(X, Y, Z, vmin=np.min(Z), vmax=np.max(Z), shading='auto')
axs[0].set_title("shading='auto' = 'nearest'")
axs[1].pcolormesh(X, Y, Z[:-1, :-1], vmin=np.min(Z), vmax=np.max(Z),
shading='flat')
axs[1].set_title("shading='flat'")
Text(0.5, 1.0, "shading='flat'")
使用规范制作关卡#
展示如何结合 Normalization 和 Colormap 实例以在 中绘制“级别” axes.Axes.pcolor
,axes.Axes.pcolormesh
并axes.Axes.imshow
以与轮廓/轮廓的级别关键字参数类似的方式键入绘图。
# make these smaller to increase the resolution
dx, dy = 0.05, 0.05
# generate 2 2d grids for the x & y bounds
y, x = np.mgrid[slice(1, 5 + dy, dy),
slice(1, 5 + dx, dx)]
z = np.sin(x)**10 + np.cos(10 + y*x) * np.cos(x)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
z = z[:-1, :-1]
levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max())
# pick the desired colormap, sensible levels, and define a normalization
# instance which takes data values and translates those into levels.
cmap = plt.colormaps['PiYG']
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
fig, (ax0, ax1) = plt.subplots(nrows=2)
im = ax0.pcolormesh(x, y, z, cmap=cmap, norm=norm)
fig.colorbar(im, ax=ax0)
ax0.set_title('pcolormesh with levels')
# contours are *point* based plots, so convert our bound into point
# centers
cf = ax1.contourf(x[:-1, :-1] + dx/2.,
y[:-1, :-1] + dy/2., z, levels=levels,
cmap=cmap)
fig.colorbar(cf, ax=ax1)
ax1.set_title('contourf with levels')
# adjust spacing between subplots so `ax1` title and `ax0` tick labels
# don't overlap
fig.tight_layout()
plt.show()
参考
此示例中显示了以下函数、方法、类和模块的使用:
脚本总运行时间:(0分1.467秒)