Search code examples
pythonmatplotlibfiguresubplot

Matplotlib - How to place figures next to each other?


I have the following code:

def compare(f,a,b,c,d,n,points):
    """Plots 2 figures - one of the color map of f, and one of the color map of a rectangle [a,b] x [c,d], split
    into n^2 subareas, using the list of points to estimate the color map"""
    #fig, axes = plt.subplots(nrows=2, ncols=2)
    q = plt.figure(1)
    colorMapList(f,a,b,c,d,n,points)
    #q.show()
    p = plt.figure(2)
    colorMap(f)
    plt.show()

The functions colorMapList and colorMap both return ax.contourf(Y,X,z).

When I have the code the way I have it, the program outputs two diagrams, one below the other. How can I have it so that the diagrams are displayed horizontally next to each other? Thanks!


Solution

  • If you want both graphs on a single figure then you can use plt.subplot(121) and plt.subplot(122). The first index is the number of rows and the second index is the number of cols. The third index is the position count of the figure layout, so if it was subplot(221) would be a 2x2 display of graphs and the 1 represents the graph in the upper left. Then, subplot(222) would be upper right, subplot(223) is bottom left, and subplot(224) is bottom right. This follow the sequence from top left to right for each row.

    However, if you want to plot 2 different figures that are side-by-side then you can look at this solution.