在python的顶部水平对齐图例

时间:2021-03-11 02:13:19

标签: 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,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()

enter image description here

1 个答案:

答案 0 :(得分:1)

ncol 参数将允许您制作水平堆叠的图例(使用 4,因为您有 4 个标签)。然后使用 'center' 位置和 bbox_to_anchor 将其放在图上方。

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

enter image description here