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.
CodePudding user response:
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.