matplotlib loop make subplot for each category

前端 未结 2 1196
自闭症患者
自闭症患者 2021-01-31 23:38

I am trying to write a loop that will make a figure with 25 subplots, 1 for each country. My code makes a figure with 25 subplots, but the plots are empty. What can I change to

2条回答
  •  暖寄归人
    2021-02-01 00:01

    You got confused between the matplotlib plotting function and the pandas plotting wrapper.
    The problem you have is that ax.plot does not have any x or y argument.

    Use ax.plot

    In that case, call it like ax.plot(df0['Date'], df0[['y1','y2']]), without x, y and title. Possibly set the title separately. Example:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    countries = np.random.choice(list("ABCDE"),size=25)
    df = pd.DataFrame({"Date" : range(200),
                        'Country' : np.repeat(countries,8),
                        'y1' : np.random.rand(200),
                        'y2' : np.random.rand(200)})
    
    fig = plt.figure()
    
    for c,num in zip(countries, xrange(1,26)):
        df0=df[df['Country']==c]
        ax = fig.add_subplot(5,5,num)
        ax.plot(df0['Date'], df0[['y1','y2']])
        ax.set_title(c)
    
    plt.tight_layout()
    plt.show()
    

    Use the pandas plotting wrapper

    In this case plot your data via df0.plot(x="Date",y =['y1','y2']).

    Example:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    countries = np.random.choice(list("ABCDE"),size=25)
    df = pd.DataFrame({"Date" : range(200),
                        'Country' : np.repeat(countries,8),
                        'y1' : np.random.rand(200),
                        'y2' : np.random.rand(200)})
    
    fig = plt.figure()
    
    for c,num in zip(countries, xrange(1,26)):
        df0=df[df['Country']==c]
        ax = fig.add_subplot(5,5,num)
        df0.plot(x="Date",y =['y1','y2'], title=c, ax=ax, legend=False)
    
    plt.tight_layout()
    plt.show()
    

提交回复
热议问题