python中的水平对齐条形图图例

python中的水平对齐条形图图例,python,matplotlib,legend,Python,Matplotlib,Legend,我已经用下面的代码制作了一个多轴图形,我无法按照我想要的方式排列图例。我的图的代码如下所示: import matplotlib.pyplot as plt import numpy as np x = np.arange(4) y = [5, 7, 4, 9] z = [9, 3, 5, 6] r = [30, 40, 45, 37] fig,ax = plt.subplots() abc = ax.bar(x,y,0.25 ) cde = ax.bar(x+0.25,z,0.25)

我已经用下面的代码制作了一个多轴图形,我无法按照我想要的方式排列图例。我的图的代码如下所示:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(4)

y = [5, 7, 4, 9]
z = [9, 3, 5, 6]
r = [30, 40, 45, 37]


fig,ax = plt.subplots()

abc = ax.bar(x,y,0.25 )
cde = ax.bar(x+0.25,z,0.25)

ax.legend((abc[0], cde[0]), ('y', 'z'),bbox_to_anchor=(0., 1.02, 1, .102) , borderaxespad=0.)
ax.set_xticks(x + 0.25 / 2)
ax.set_xticklabels(('A', 'B', 'C', 'D'))

ax2 = ax.twinx()
efg = ax2.plot(x+0.25/2,r,color = 'black',label = "r")
ax2.legend(bbox_to_anchor=(0.11,1.07) , borderaxespad=0.)

plt.show()
它显示的图表是这样的

右上方的图例垂直对齐,但我希望它们水平对齐。我找不到这方面的任何文档。我希望它们如下图所示。


谢谢您需要使用
ncol
参数,该参数设置要在中使用的列数,例如
ncol=2
将为您提供两列

ax.legend(..., ncol=2)
然后,您可以使用
loc
参数和
bbox\u to\u锚定
,找到合理的参数并使两个图例相互对齐:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(4)

y = [5, 7, 4, 9]
z = [9, 3, 5, 6]
r = [30, 40, 45, 37]


fig,ax = plt.subplots()

abc = ax.bar(x,y,0.25 )
cde = ax.bar(x+0.25,z,0.25)

ax.legend((abc[0], cde[0]), ('y', 'z'),loc="lower right", bbox_to_anchor=(1., 1.02) , borderaxespad=0., ncol=2)
ax.set_xticks(x + 0.25 / 2)
ax.set_xticklabels(('A', 'B', 'C', 'D'))

ax2 = ax.twinx()
efg = ax2.plot(x+0.25/2,r,color = 'black',label = "r")
ax2.legend(bbox_to_anchor=(0,1.02),loc="lower left", borderaxespad=0.)

plt.show()