Reputation: 761
I am working on plotting bar chart .. i need to align legend horizontally and on center on top of the bar plot .. can anyone help me .. i saw other codes but i am not able to understand and integrate with my code
import numpy as np
import matplotlib.pyplot as plt
# set width of bars
barWidth = 0.1
# set heights of bars
a = [3,4, 15, 10, 12]
b = [2,13,4,19,1]
c = [12,3,7,8,4]
d = [12, 13,4,7,14]
# Set position of bar on X axis
r1 = np.arange(len(a))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]
r4 = [x + barWidth for x in r3]
# Make the plot
plt.bar(r1, a, width=barWidth,label='a')
plt.bar(r2, b, width=barWidth,label='b')
plt.bar(r3, c, width=barWidth,label='c')
plt.bar(r4, d, width=barWidth,label='d')
#plt.bar(r3, bars3, color='#2d7f5e', width=barWidth, edgecolor='white', label='var3')
plt.xticks([r + barWidth for r in range(len(a))], ['A','B', 'C', 'D', 'E'])
# Create legend & Show graphic
plt.legend()
plt.show()
Upvotes: 1
Views: 1575
Reputation: 59549
The ncol
argument will allow you to make a horizontally stacked legend (Use 4 because you have 4 labels). Then use the 'center'
location and bbox_to_anchor
to put it above the plot.
# ....
# All your same code just modify the legend line:
plt.legend(ncol=4, loc='center', bbox_to_anchor=(0.5, 1.06))
plt.show()
Upvotes: 3