Search code examples
pythonmatplotlibsubplot

Plot custom functions in each subplot


I've got some custom functions which plot the results of some analysis. I want to show each plot in a subplot of a figure, something like

---------------------------
|   Plot 1   |   Plot 2   |
|            |            |
---------------------------
|   Plot 3   |   Plot 4   |
|            |            |
---------------------------

Here's an MWE:

import numpy as np
import matplotlib.pyplot as plt

def plot_sin():
    x = np.linspace(0, 10)
    y = np.sin(x)
    plt.plot(x, y)
    plt.title('Just a sine curve')

def plot_int():
    x = np.linspace(-10, 10)
    y = np.sin(x) / x
    plt.plot(x, y)
    plt.title('Looks like an interference pattern')

def plot_hist():
    x = np.random.normal(0.2, 0.05, 1000)
    plt.hist(x)
    plt.title('Oh look, it\'s a histogram')

def plot_sin_cos():
    x = np.linspace(-3*np.pi, 3*np.pi, 1000)
    y = np.sin(x) / np.cos(x)
    plt.plot(x, y)
    plt.title('Yet another siney plot')

plot_sin()
plot_int()
plot_hist()
plot_sin_cos()

fig, ax = plt.subplots(2, 2)
ax[0, 0].plot_sin()
ax[1, 0].plot_int()
ax[0, 1].plot_hist()
ax[1, 1].plot_sin_cos()

but of course 'AxesSubplot' object has no attribute 'plot_sin'. How can I have each of my functions plotted in a separate subplot?


Solution

  • I would do something like this:

    # pass the axis here and the other functions as well
    def plot_sin(ax):
        x = np.linspace(0, 10)
        y = np.sin(x)
        ax.plot(x, y)
        ax.set_title('Just a sine curve')
    
    fig, ax = plt.subplots(2,2)
    plot_sin(ax[0,0])