【问题标题】:Changing position of matplotlib plot legend更改 matplotlib 图图例的位置
【发布时间】:2021-07-11 07:46:44
【问题描述】:

我想更改绘图图例相对于绘图位置的位置。这是情节的代码:

    fig = plt.subplot(122)
    legend = []
    plt.plot(k_array, NDCG, 'red')
    legend.append("utility overall NDCG")
    if data_loader.GSQb:
        plt.plot(k_array, GSQNDCG, 'orange')
        legend.append("GSQ NDCG")
    if data_loader.BSQb:
        plt.plot(k_array, BSQNDCG, 'purple')
        legend.append("BSQ NDCG")
    if data_loader.GWQb:
        plt.plot(k_array, GWQNDCG, 'black')
        legend.append("GWQ NDCG")
    fig.legend(legend)
    #plt.legend(bbox_to_anchor=(-1, 1),fontsize= 'large')
    plt.savefig(metaCat + " best utility NDCGS")

下面是生成的 PNG 的样子:

如果可能,我想让图例出现在绘图左侧的大空间中(最好具有相同的大小)。我怎样才能做到这一点?

编辑:我已经阅读了 the docsMoving matplotlib legend outside of the axis makes it cutoff by the figure box,但我仍然无法弄清楚。

【问题讨论】:

    标签: python matplotlib data-science


    【解决方案1】:

    写得很好in the docs。您需要使用loc 参数来选择图例的位置。

    也尝试使用bbox_to_anchor=(x, y, width, height)(可能使用负值)将图例移到图外。

    【讨论】:

      【解决方案2】:

      你可以试试这个

          fig = plt.subplot(122)
      legend = []
      plt.plot(k_array, NDCG, 'red')
      legend.append("utility overall NDCG")
      if data_loader.GSQb:
          plt.plot(k_array, GSQNDCG, 'orange')
          legend.append("GSQ NDCG")
      if data_loader.BSQb:
          plt.plot(k_array, BSQNDCG, 'purple')
          legend.append("BSQ NDCG")
      if data_loader.GWQb:
          plt.plot(k_array, GWQNDCG, 'black')
          legend.append("GWQ NDCG")
      fig.legend(legend)
      plt.legend(bbox_to_anchor=(-1, 1),fontsize= 'large', loc='upper left')
      plt.savefig(metaCat + " best utility NDCGS")
      

      【讨论】:

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