【问题标题】:Python matplotlib legend below multiple graphs多个图下方的Python matplotlib图例
【发布时间】:2015-01-07 17:46:10
【问题描述】:

我在一个图中有 2 个图表,我希望图例出现在它们下方的空白处。出于某种原因,它总是在其中一个馅饼的顶部,即使我做“底部”。

另外,我使用了两次“title”属性来分别标记每个图表。我怎样才能移动图表下方的标签? title 属性似乎没有“loc”属性。

谢谢!

labels = 'a', 'b', 'c', 'd'
fracsQuads = [6, 14, 1, 79]
fracsTrips = [11, 16, 7, 66]
colors=['Goldenrod', 'LimeGreen', 'Crimson', 'DeepSkyBlue']

explode=(0, 0, 0, 0)

# Make square figures and axes

the_grid = GridSpec(1, 2)

plt.subplot(the_grid[0, 0], aspect=1)

plt.pie(fracsQuads, autopct='%1.0f%%', colors=colors, pctdistance=1.2)

plt.title('Four knockouts')
plt.subplot(the_grid[0, 1], aspect=1)


plt.pie(fracsTrips, explode=explode, autopct='%.0f%%', colors=colors, pctdistance=1.2)
plt.title('Three knockouts')

#plt.legend(labels, loc='best')

font = {'family' : 'normal',
        'weight' : 'normal',
        'size'   : 14}

matplotlib.rc('font', **font)

plt.show()

plt.savefig('pythonFigureTest.png', facecolor='white', transparent=True)

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    关键是您没有标记轴。因此,图例将始终相对于正确的图放置,因为这是最后创建的轴。 您可以使用bbox_to_anchor 手动移动到图例框。此外,我删除了标题并使用figtext() 将文本手动放在图下方。

    下面的代码应该做到这一点:

    font = {'family' : 'normal',
            'weight' : 'normal',
            'size'   : 14}
    
    rcParams.update(font)
    
    labels = 'a', 'b', 'c', 'd'
    fracsQuads = [6, 14, 1, 79]
    fracsTrips = [11, 16, 7, 66]
    colors=['Goldenrod', 'LimeGreen', 'Crimson', 'DeepSkyBlue']
    
    explode=(0, 0, 0, 0)
    
    # Make square figures and axes
    
    the_grid = GridSpec(1, 2)
    
    ax1 = plt.subplot(the_grid[0, 0], aspect=1)
    ax2 = plt.subplot(the_grid[0, 1], aspect=1)
    
    ax1.pie(fracsQuads, autopct='%1.0f%%', colors=colors, pctdistance=1.2)
    ax2.pie(fracsTrips, explode=explode, autopct='%.0f%%', colors=colors, pctdistance=1.2)
    
    plt.figtext(0.19,0.2,'Four knockouts')
    plt.figtext(0.61,0.2,'Three knockouts')
    
    ax1.legend(labels, loc='lower center',bbox_to_anchor=(1.1, -0.1),
                     prop={'size':11})
    
    plt.show()
    

    我在图例框中使用了小字体,这样它就可以很好地适应两者之间的关系。如果您有更长的文本,您可能不得不摆弄数字。

    【讨论】:

    • 谢谢 - 这太棒了!
    猜你喜欢
    • 2020-11-26
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 2014-10-06
    • 1970-01-01
    • 2018-02-26
    • 2016-10-15
    相关资源
    最近更新 更多