【问题标题】:Horizontally align bar plot legends in python在python中水平对齐条形图图例
【发布时间】:2017-04-20 13:54:42
【问题描述】:

我使用以下代码制作了一个多轴图,但我无法按照我的意愿排列图例。我的图表代码如下:

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

它显示的图形是这样的

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

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    您需要使用ncol 参数,它设置要在legend 中使用的列数,例如ncol=2 会给你两列。

    ax.legend(..., ncol=2)
    

    然后您可以使用loc 参数和bbox_to_anchor 查看how to place the 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)
    
    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多