0

I want to change the position of a plot legend relative to the position of the plot. Here's the code for the plot:

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

And here's how the resulting PNG looks: enter image description here

If possible, I'd like to make the legend appear in the large space to the left of the plot (preferably with the same size). How can I make this happen?

Edit: I've read through the docs and Moving matplotlib legend outside of the axis makes it cutoff by the figure box, and I'm still having trouble figuring it out.

javaMan
  • 35
  • 5

2 Answers2

0

It's well written in the docs. You need to use the loc parameter to select the location of the legend.

Try to use bbox_to_anchor=(x, y, width, height) as well (maybe with negative values) to move the legend outside of the figure.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Kulikr
  • 1
  • 1
0

Yoy may try this

    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")
alihank
  • 98
  • 2
  • 10