Search code examples
pythonpandasmatplotlibseabornsubplot

How to plot multiple dataframes in subplots


I have a few Pandas DataFrames sharing the same value scale, but having different columns and indices. When invoking df.plot(), I get separate plot images. what I really want is to have them all in the same plot as subplots, but I'm unfortunately failing to come up with a solution to how and would highly appreciate some help.


Solution

  • You can manually create the subplots with matplotlib, and then plot the dataframes on a specific subplot using the ax keyword. For example for 4 subplots (2x2):

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(nrows=2, ncols=2)
    
    df1.plot(ax=axes[0,0])
    df2.plot(ax=axes[0,1])
    ...
    

    Here axes is an array which holds the different subplot axes, and you can access one just by indexing axes.
    If you want a shared x-axis, then you can provide sharex=True to plt.subplots.