注意
跳转至页面底部下载完整示例代码。
Hatchcolor 演示#
可以使用 hatchcolor 参数设置剖面线(hatch)的颜色。以下示例展示了如何在 Patch 和 Collection 中使用 hatchcolor 参数来设置剖面线颜色。
更多关于剖面线的使用示例,请参见 Hatch 演示。
Patch Hatchcolor#
此示例展示了如何使用 hatchcolor 参数设置矩形和条形图中剖面线的颜色。hatchcolor 参数适用于 Patch、Patch 的子类以及传递给 Patch 的方法。
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
from matplotlib.patches import Rectangle
fig, (ax1, ax2) = plt.subplots(1, 2)
# Rectangle with red hatch color and black edge color
ax1.add_patch(Rectangle((0.1, 0.5), 0.8, 0.3, hatch=".", hatchcolor='red',
edgecolor='black', lw=2))
# If hatchcolor is not passed, the hatch will match the edge color
ax1.add_patch(Rectangle((0.1, 0.1), 0.8, 0.3, hatch='x', edgecolor='orange', lw=2))
x = np.arange(1, 5)
y = np.arange(1, 5)
ax2.bar(x, y, facecolor='none', edgecolor='red', hatch='//', hatchcolor='blue')
ax2.set_xlim(0, 5)
ax2.set_ylim(0, 5)

Collection Hatchcolor#
以下示例展示了如何使用 hatchcolor 参数设置散点图中剖面线的颜色。hatchcolor 参数也可以传递给 Collection、Collection 的子类以及传递给 Collection 的方法。
fig, ax = plt.subplots()
num_points_x = 10
num_points_y = 9
x = np.linspace(0, 1, num_points_x)
y = np.linspace(0, 1, num_points_y)
X, Y = np.meshgrid(x, y)
X[1::2, :] += (x[1] - x[0]) / 2 # stagger every alternate row
# As ax.scatter (PathCollection) is drawn row by row, setting hatchcolors to the
# first row is enough, as the colors will be cycled through for the next rows.
colors = [cm.rainbow(val) for val in x]
ax.scatter(
X.ravel(),
Y.ravel(),
s=1700,
facecolor="none",
edgecolor="gray",
linewidth=2,
marker="h", # Use hexagon as marker
hatch="xxx",
hatchcolor=colors,
)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()

参考
本示例展示了以下函数、方法、类和模块的使用
脚本总运行时间:(0 分 1.016 秒)