【问题标题】:How to change order and grouping of entries in a matplotlib legend?如何更改 matplotlib 图例中条目的顺序和分组?
【发布时间】:2023-01-16 23:38:26
【问题描述】:

这就是我的传奇现在的样子:

我希望它看起来像这样:

我目前使用的唯一变量是ncols,例如:plt.legend(..., ncols=4)

【问题讨论】:

    标签: python matplotlib plot plotly


    【解决方案1】:

    我不认为这是明确支持的。您可以通过向图例添加额外的虚假条目来解决它(在您的情况下为 3)。考虑:

    import numpy as np
    import matplotlib.pyplot as plt
    
    plt.figure()
    
    # Actual data
    for i in range(13):
        plt.plot(np.random.random(), np.random.random(), '.', label=chr(ord('A') + i))
    
    # Fake data, for the legend
    plt.plot(0, np.zeros([1, 3]), '.', ms=0, label=' ')
    
    plt.legend(ncol=4)
    plt.show()  # or plt.savefig('figname.png')
    

    在这里,我使用了 0 的标记大小 (ms),确保绘制的假数据点不会出现在绘图或图例上。

    【讨论】:

      【解决方案2】:

      您可以添加一些虚拟图例句柄来填充空白区域:

      from matplotlib import pyplot as plt
      
      labels = 'abcdefghijklm'
      for i, (label) in enumerate(labels):
          plt.bar([i], (i + 1) ** 2, color=plt.cm.turbo_r(i / len(labels)), label=label)
      handles, labels = plt.gca().get_legend_handles_labels()
      dummy_handle = plt.Rectangle((0, 0), 0, 0, color='none', label='')
      plt.legend(handles=handles + 3*[dummy_handle], ncol=4)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2021-07-06
        • 2016-12-30
        • 1970-01-01
        • 2019-06-19
        • 1970-01-01
        • 2020-06-21
        • 2014-05-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多