Python 实例|matplotlib|pcolormesh 函数着色规则

文章介绍了matplotlib库中pcolormesh函数的使用,特别是shading参数对网格着色的影响。通过示例展示了flat、nearest和gouraud三种着色方式,以及如何结合numpy生成和可视化二维数据矩阵Z。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pcolormesh 的官方文档:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.pcolormesh.html

pcolormesh 着色规则的官方文档:https://matplotlib.org/stable/gallery/images_contours_and_fields/pcolormesh_grids.html

matplotlib.axes.Axes.pcolormesh 函数和 matplotlib.axes.Axes.pcolor 函数均有 shading 参数可以用于网格的布局和网格点之间的着色。如果令 Z 表示颜色,XY 表示网格,那么如果 Z 的形状为 m × n m \times n m×n,则 XY 的 shape 可以是 ( m + 1 ) × ( n + 1 ) (m+1)\times(n+1) (m+1)×(n+1) m × n m \times n m×n,具体取决于 shading 参数的选择。

>>> from matplotlib import pyplot as plt
... import numpy as np
... np.random.seed(0)

构造测试数据如下:

>>> n_rows = 3
... n_cols = 5
... x = np.arange(n_cols + 1)
... y = np.arange(n_rows + 1)
... Z = np.random.randint(0, 3, (n_rows, n_cols))
>>> Z
[[0 1 0 1 1]
 [2 0 2 0 0]
 [0 2 1 2 2]]

shading = Flat

>>> fig, ax = plt.subplots()
... ax.pcolormesh(x, y, Z, shading="flat", vmin=np.min(Z), vmax=np.max(Z))
... X, Y = np.meshgrid(x, y)
... ax.plot(X.flat, Y.flat, "o", color="m")
... ax.set_xlim(-0.5, 5.5)
... ax.set_ylim(-0.5, 3.5)
... ax.set_title("shading=flat")
Example 1

shading = nearest

>>> fig, ax = plt.subplots()
... ax.pcolormesh(x[:-1], y[:-1], Z, shading="nearest", vmin=np.min(Z), vmax=np.max(Z))
... X, Y = np.meshgrid(x, y)
... ax.plot(X.flat, Y.flat, "o", color="m")
... ax.set_xlim(-0.5, 5.5)
... ax.set_ylim(-0.5, 3.5)
... ax.set_title("shading=nearest")

Example 2

shading = gouraud

fig, ax = plt.subplots()
ax.pcolormesh(x[:-1], y[:-1], Z, shading="gouraud", vmin=np.min(Z), vmax=np.max(Z))
X, Y = np.meshgrid(x, y)
ax.plot(X.flat, Y.flat, "o", color="m")
ax.set_xlim(-0.5, 5.5)
ax.set_ylim(-0.5, 3.5)
ax.set_title("shading=gouraud")

Example 3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值