简体   繁体   中英

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. I tried to plot but I couldn't generate proper legends with this code:

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. Please help to generate this bar plot with different hatch and edge color with proper legend in matplotlib. Thanks in adavance.

Your can combine the line1 and line2 with a tuple in the handle lists.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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