How can I plot separate Pandas DataFrames as subplots?

后端 未结 9 1989
离开以前
离开以前 2020-11-22 17:00

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

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 17:54

    You can plot multiple subplots of multiple pandas data frames using matplotlib with a simple trick of making a list of all data frame. Then using the for loop for plotting subplots.

    Working code:

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    # dataframe sample data
    df1 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
    df2 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
    df3 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
    df4 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
    df5 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
    df6 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
    #define number of rows and columns for subplots
    nrow=3
    ncol=2
    # make a list of all dataframes 
    df_list = [df1 ,df2, df3, df4, df5, df6]
    fig, axes = plt.subplots(nrow, ncol)
    # plot counter
    count=0
    for r in range(nrow):
        for c in range(ncol):
            df_list[count].plot(ax=axes[r,c])
            count=+1
    

    Using this code you can plot subplots in any configuration. You need to just define number of rows nrow and number of columns ncol. Also, you need to make list of data frames df_list which you wanted to plot.

提交回复
热议问题