备注
前往结尾 下载完整示例代码。
Hatch 样式参考#
在 Matplotlib 中,可以在大多数多边形上添加阴影线,包括 bar、fill_between、contourf 以及 Polygon 的子类。目前,PS、PDF、SVG、macosx 和 Agg 后端支持阴影线。WX 和 Cairo 后端目前不支持阴影线。
另请参阅 等值线填充图案 以查看使用 contourf 的示例,以及 Hatch 演示 以获取更多使用示例。
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
fig, axs = plt.subplots(2, 5, layout='constrained', figsize=(6.4, 3.2))
hatches = ['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*']
def hatches_plot(ax, h):
ax.add_patch(Rectangle((0, 0), 2, 2, fill=False, hatch=h))
ax.text(1, -0.5, f"' {h} '", size=15, ha="center")
ax.axis('equal')
ax.axis('off')
for ax, h in zip(axs.flat, hatches):
hatches_plot(ax, h)

可以通过重复阴影图案来增加密度。
fig, axs = plt.subplots(2, 5, layout='constrained', figsize=(6.4, 3.2))
hatches = ['//', '\\\\', '||', '--', '++', 'xx', 'oo', 'OO', '..', '**']
for ax, h in zip(axs.flat, hatches):
hatches_plot(ax, h)

可以通过组合不同的填充图案来创建新的图案。
fig, axs = plt.subplots(2, 5, layout='constrained', figsize=(6.4, 3.2))
hatches = ['/o', '\\|', '|*', '-\\', '+o', 'x*', 'o-', 'O|', 'O.', '*-']
for ax, h in zip(axs.flat, hatches):
hatches_plot(ax, h)

参考文献
以下示例展示了以下函数、方法、类和模块的使用: