简体   繁体   English

如何 plot 使用 matplotlib 绘制具有不同剖面线和边缘颜色且带有图例的条形图?

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

I would like to plot a barplot where bars have a different hatch and edge color using Matplotlib with its proper legends.我想要 plot 条形图,其中条形图使用 Matplotlib 及其适当的图例具有不同的阴影线和边缘颜色。 I tried to plot but I couldn't generate proper legends with this code:我试过 plot 但我无法用这段代码生成正确的图例:

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()

In the above code, the legend by using variable line1 shows hatch but edge color is not visible and the legend by line2 shows edge color but hatch is not visible.在上面的代码中,使用变量 line1 的图例显示影线但边缘颜色不可见,line2 的图例显示边缘颜色但影线不可见。 Please help to generate this bar plot with different hatch and edge color with proper legend in matplotlib. Thanks in adavance.请帮助生成此条 plot,具有不同的阴影线和边缘颜色,并在 matplotlib 中使用适当的图例。在此先感谢。

Your can combine the line1 and line2 with a tuple in the handle lists.您可以将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()

在此处输入图像描述

You can see the doc .你可以看到文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM