pythonmatplotlibgraph

What to do with `matplotlib` graphs given in a list that a function returns (or what is an alternative function architecture)?


I have a function that works something like this.

import numpy as np
import matplotlib.pyplot as plt

def plot_from_dave(n = 100, r = 10):
    
    my_list = []
    
    for i in range(r):
        
        fig, ax = plt.subplots()
        x = np.random.normal(0, 1, n)
        y = np.random.normal(0, 1, n)
        ax.scatter(x, y)
        
        my_list.append((fig, ax))
    
    return(my_list)

The function creates many plots and then saves the figure-axis tuples to a list that is returned.

I now want to access those figures and axes for downstream customization of the plots. However, accessing them has been problematic. For instance, in the below, I get nothing.

np.random.seed(2024)
plot_list = plot_from_dave(10, 3)
plot_list[0]
plt.show()

How can I access these figures and axes to apply further customization outside of the function? Alternatively, how can I set up the function to allow customization of the plots?


Solution

  • You return a list, so you can either index it or loop over it:

    import numpy as np
    import matplotlib.pyplot as plt
    
    
    def plot_from_dave(n=100, r=10):
        my_list = []
    
        for i in range(r):
            fig, ax = plt.subplots()
            x = np.random.normal(0, 1, n)
            y = np.random.normal(0, 1, n)
            ax.scatter(x, y)
    
            my_list.append((fig, ax))
    
        return (my_list)
    
    
    figs = plot_from_dave(r=4)
    for i, (fig, ax) in enumerate(figs):
        ax.set_title(f'Title {i+1}')
        # set the color of the dots to a random color
        ax.collections[0].set_facecolor(np.random.rand(3))
        fig.show()
    
    figs[2][1].set_title('Title special 3')
    figs[2][1].collections[0].set_facecolor('red')
    figs[2][0].show()
    

    This generates 4 plots (and then displays them), giving them different titles and colours after plot_from_dave() completes and returns. It also specifically selects the 3rd one and sets its title and a specific colour and then shows it again.

    Note that you don't have to use enumerate() - my example only does so to get a nice index number that can be used to give them the numbered titles. If you don't need something like that, you can of course just for fix, ax in figs:.