如何使用 matplotlib 绘制带有图例的不同阴影线和边缘颜色的条形图?

How to plot a barplot with different hatch and edge color with legends using matplotlib?

我想使用 Matplotlib 及其适当的图例绘制一个条形图,其中条形图具有不同的阴影线和边缘颜色。我尝试绘制但无法使用此代码生成正确的图例:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
# draw hatch
line1 = ax.bar(range(1, 5), range(1, 5), color='none', edgecolor='red', hatch="/", lw=1., zorder = 0)
# draw edge
line2 = ax.bar(range(1, 5), range(1, 5), color='none', edgecolor='k', zorder=1, lw=2.)

ax.set_xticks([1.5, 2.5, 3.5, 4.5])
ax.legend([line1[0]],['hatch'])
plt.show()

在上面的代码中,使用变量 line1 的图例显示了影线,但边缘颜色不可见,而 line2 的图例显示了边缘颜色,但影线不可见。请帮助在 matplotlib 中使用适当的图例生成具有不同阴影线和边缘颜色的条形图。提前致谢。

您可以在句柄列表中将 line1line2 与一个元组结合起来。

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
# draw hatch
line1 = ax.bar(range(1, 5), range(1, 5), color='none', edgecolor='r', hatch="/", lw=1., zorder = 0)
# draw edge
line2 = ax.bar(range(1, 5), range(1, 5), color='none', edgecolor='k', zorder=1, lw=2.)

ax.set_xticks([1.5, 2.5, 3.5, 4.5])
ax.legend([(line1, line2)],['hatch'])  
plt.show()

您可以看到 doc.