【问题标题】:Reverse the order of a legend反转图例的顺序
【发布时间】:2016-04-07 04:11:49
【问题描述】:

我使用以下代码来绘制条形图,并且需要以相反的顺序呈现图例。我该怎么做?

colorsArr = plt.cm.BuPu(np.linspace(0, 0.5, len(C2)))
p = numpy.empty(len(C2), dtype=object)
plt.figure(figsize=(11, 11))

prevBar = 0
for index in range(len(C2)):
    plt.bar(ind, C2[index], width, bottom=prevBar, color=colorsArr[index],
            label=C0[index])
    prevBar = prevBar + C2[index]

# Positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i + (width/2) for i in ind]

plt.ylabel('Home Category')
plt.title('Affinity - Retail Details(Home category)')

# Set the x ticks with names
plt.xticks(tick_pos, C1)
plt.yticks(np.arange(0, 70000, 3000))
plt.legend(title="Line", loc='upper left')

# Set a buffer around the edge
plt.xlim(-width*2, width*2)
plt.show()

【问题讨论】:

    标签: python matplotlib reverse legend


    【解决方案1】:

    你可以打电话

    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')
    

    import numpy as np
    import matplotlib.pyplot as plt
    np.random.seed(2016)
    
    C0 = list('ABCDEF')
    C2 = np.random.randint(20000, size=(len(C0), 3))
    width = 1.0
    C1 = ['foo', 'bar', 'baz']
    ind = np.linspace(-width, width, len(C1))
    
    
    colorsArr = plt.cm.BuPu(np.linspace(0, 0.5, len(C2)))
    fig = plt.figure(figsize=(11,11))
    ax = fig.add_subplot(1, 1, 1)
    
    prevBar = 0
    for height, color, label in zip(C2, colorsArr, C0):
        h = ax.bar(ind, height, width, bottom=prevBar, color=color, label=label)
        prevBar = prevBar + height
    
    plt.ylabel('Home Category')
    plt.title('Affinity - Retail Details(Home category)')
    
    # positions of the x-axis ticks (center of the bars as bar labels)
    tick_pos = [i+(width/2.0) for i in ind]
    # set the x ticks with names
    plt.xticks(tick_pos, C1)
    plt.yticks(np.arange(0,70000,3000))
    
    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      或者你可以使用更简单的

      handles, labels = ax.get_legend_handles_labels()
      ax.legend(reversed(handles), reversed(labels), title='Line', loc='upper left')
      

      【讨论】:

      • ax.legend(*map(reversed, ax.get_legend_handles_labels()), ...)
      • @user66081:请解释您的更正,因为原始解决方案似乎工作得很好,并且类似于使用带有负步长切片且也没有映射的索引的选定答案。
      • @mins:我想原因是你不需要记住哪个先出现,你可以在 IDE 的建议列表中找到 get_legend_handles_labels。 “加号”,负步片很难看。
      【解决方案3】:

      对图例垂直间距使用负数,如下所示:

      matplotlib.pyplot.stackplot(X, *revDataValues,
          linewidth=1.0,
          edgecolor='black')
      
      matplotlib.pyplot.legend(revNames,
          loc=6, bbox_to_anchor=(1.05, 0.5),
          labelspacing=-2.5, frameon=False,         # reverse legend
          fontsize=9.0)
      

      Stacked Area Chart with reversed legend

      【讨论】:

      • 什么是 *revDataValues?
      • 我认为这行不通。我想切换图例中的项目,而不是情节。
      • 我喜欢它的优雅——但它会导致我传说中的一些物品掉到盒子外面。
      • 这是我见过的最被低估的答案 - 非常优雅
      【解决方案4】:

      我没有对此进行测试,因为我没有您的数据,但这是基于controlling legend entries 上的文档。

      handles = []
      for index in range(len(C2)):
          h = plt.bar(ind, C2[index], width, bottom=prevBar, color=colorsArr[index], label=C0[index])
          handles.append(h)
          prevBar = prevBar + C2[index]
      
      plt.legend(title="Line", loc='upper left', handles=handles[::-1])
      

      【讨论】:

      • 这个答案中的C2 是什么?
      • 我想和问题中的C2 一样
      • AttributeError: 'list' object has no attribute 'get_label'
      • 只是用逗号固定:h, = plt.plot[...]
      猜你喜欢
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 2017-05-06
      • 2012-04-05
      • 2012-10-09
      相关资源
      最近更新 更多