0

I'm trying to place the legend in the space underneath a matplotlib plot. I'm creating each subplot with a unique identifier then using plt.figure() to adjust the size of the plot. When I specify a plot size, the space around the plot disappears (the PNG tightens the layout around the plot). Here's my code:

        fig = plt.subplot(111)
        plt.figure(111,figsize=(3,3))
        plots = []
        legend = []
        #fig.set_xlim([0, 20])
        #fig.set_ylim([0, 1])
        #ticks = list(range(len(k_array)))
        #plt.xticks(ticks, k_array)
        plt.plot(k_array, avgNDCG, 'red')
        legend.append("eco overall F1")
        if data_loader.GSQb:
            legend.append("GSQ F1")
            plt.plot(k_array, avgGSQNDCG, 'orange')
        if data_loader.BSQb:
            legend.append("BSQ F1")
            plt.plot(k_array, avgBSQNDCG, 'purple')
        if data_loader.GWQb:
            legend.append("GWQ F1")
            plt.plot(k_array, avgGWQNDCG, 'black')
        if data_loader.BWQb:
            legend.append("BWQ F1")
            plt.plot(k_array, avgBWQNDCG, 'green')
        if data_loader.GAQb:
            legend.append("GAQ F1")
            plt.plot(k_array, avgGAQNDCG, 'blue')
        fig.legend(legend, loc='center', bbox_to_anchor=(0, 0, .7, -2),fontsize='xx-small')
        plt.savefig("RARE " + metaCat + " best avg NDCG scores")

When I comment out plt.figure(111,figsize=(3,3)), the white space underneath and around the plot is visible: enter image description here

But when I uncomment it:

enter image description here

Please help me understand how I can modify the plotsize, legend and layout spacing to make it look more like 1 but with a bigger plot.

1
  • 1
    Why not add the legend to the axes instead of the figure? Commented Jul 13, 2021 at 4:38

1 Answer 1

2
  1. If you add labels to your plot functions, then you won't have to supply legend() with handles and labels - this is more convenient.

  2. I would recommend using a loop structure instead of multiple if statements.

  3. Regarding the legend, using ncol parameter is going to help you a lot here. You may find the matplotlib documentation legend tutorial helpful

  4. If you're working with multiple subplots with different sizes, then I'd recommend using gridspec, otherwise just use plt.subplots() with ncols and nrows parameters. For example:

    fig, axes = plt.subplots(ncols=2, nrows=5, figsize=(12,12))
    axes = axes.flatten() #this results in a 1d array of 10 axes

I simulated your data and implemented what I think you are looking for below.

enter image description here

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

#simulate data
df = pd.DataFrame({'x' : [1, 2, 3]})
for i in range(11):     
    df['Line_' + str(i)] = np.random.random_sample(3)

fig, ax = plt.subplots(figsize=(12,2.5))

# Change x and y values for troubleshooting purposes
ax.plot(df.x, df.Line_1, 'red', label='eco overall F1')

# This would be a good place to implement a for loop 
# Change all conditions to true for troubleshooting purposes
if True:
    ax.plot(df.x, df.Line_1, 'orange', label='GSQ F1')
if True:
    ax.plot(df.x, df.Line_2, 'purple', label='BSQ F1')
if True:
    ax.plot(df.x, df.Line_3, 'black', label='GWQ F1')
if True:
    ax.plot(df.x, df.Line_4, 'green', label='BWQ F1')
if True:
    ax.plot(df.x, df.Line_5, 'blue', label='GAQ F1')

legend = ax.legend(ncol=4, bbox_to_anchor=(0.5,-0.5), loc='lower center', edgecolor='w')
hide_spines = [ax.spines[x].set_visible(False) for x in ['top','right']]
Sign up to request clarification or add additional context in comments.

2 Comments

getting a blank graph with this code @Coup (given that the NDCG arrays are not empty) fig, ax = plt.subplots(figsize=(12, 2.5)) if data_loader.GSQb: ax.plot(k_array, avgGSQNDCG,'orange', label='GSQ NDCG') if data_loader.BSQb: ax.plot(k_array, avgBSQNDCG,'purple', label='BSQ NDCG') legend = ax.legend(ncol=4, bbox_to_anchor=(0.5, .8), loc='lower center', edgecolor='w') plt.savefig("RARE " + metaCat + " best avg NDCG scores")
hard to say, but most likely an issue with true/false if statements or with x/y variables. Try making 'if True' to see if that plots it otherwise try some basic x and y values or look at your data to see what's going on. Then try simplifying what you're plotting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.