在python中水平对齐顶部的图例

在python中水平对齐顶部的图例,python,pandas,matplotlib,Python,Pandas,Matplotlib,我正在绘制条形图。。我需要将图例水平对齐,并位于条形图顶部的中心。。有人能帮我吗。。我看到了其他代码,但我无法理解和集成我的代码 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,

我正在绘制条形图。。我需要将图例水平对齐,并位于条形图顶部的中心。。有人能帮我吗。。我看到了其他代码,但我无法理解和集成我的代码

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

使用
ncol
参数可以创建一个水平堆叠的图例(使用4,因为您有4个标签)。然后使用
'center'
位置和
bbox\u to\u锚定
将其置于绘图上方

# ....
# All your same code just modify the legend line:
plt.legend(ncol=4, loc='center', bbox_to_anchor=(0.5, 1.06))
plt.show()