Home > Back-end >  Define fontsize for the legend text of every subplot of pandas figure
Define fontsize for the legend text of every subplot of pandas figure

Time:09-22

I have multiple dataframes for each of which I plot the performance metrics. Each dataframe looks like (the number of columns is different in every df):

    index,jack,steve,bob,sandra,helen,tracy
    1,300,100,110,500,120,100
    2,30,20,150,200,10,120
    3,320,110,190,50,12,130
    4,300,100,110,500,120,100 
    5,400,120,100,450,100,90

I want to plot each of the columns on the separate subplot of the same figure and save it in the png file.

I can't find how I can change the fontsize of the legend (the names of the students in the given example), when I'm using the following snippet with plt.legend only the last legend size is updated, but not every one of the subplot's legends.

def plot_subplot(df, group):
    ax = df.plot(subplots=True, fontsize=20, figsize=(80,40))
    plt.legend(loc='best', prop={'size': 30})
    ax[0].get_figure().savefig("{}.png".format(group), bbox_inches='tight', dpi=100)

Because the number of columns in each dataframe is different, I don't know in advance the number of subplots the function will produce for a given plot. I'm using the subplots=True parameter and not defining manually the position of each subplot via ax1, ax2 etc. That's why I'm looking for a solution compatible with this use case. enter image description here

CodePudding user response:

The issue is that df.plot currently returns a list of Axes (due to subplots=True), so you should iterate ax:

def plot_subplot(df, group):
    ax = df.plot(subplots=True, fontsize=20, figsize=(80, 40))
    
    # iterate all Axes
    for a in ax:
        a.legend(loc='best', prop={'size': 30})
    
    ax[0].get_figure().savefig('{}.png'.format(group), bbox_inches='tight', dpi=100)

  • Related