Search code examples
pythonpandasmatplotlibboxplotsubplot

Generate a subplot with ylim in df.boxplot()


I have the following code:

df.boxplot(column = ['rate'], by = 'age', figsize=(9,7))

However, this boxplot has an outlier that shows really small the boxes. I need to code the following:

#1st Subplot
df.boxplot(column = ['rate'], by = 'age', figsize=(9,7))

#2nd Subplot
df.boxplot(column = ['rate'], by = 'age', figsize=(9,7))
plt.ylim(0,2)

So this means I need a 2x1 or 1x2 subplots to show: #1 Original boxplot and #2 A zoom boxplot (ylim(0,2))

¿How can I approach this subplot?


Solution

  • Try passing the subplot axes to the pandas plots explicitly, then you can adjust their limits individually:

    import matplotlib.pyplot as plt
    
    fig, axarray = plt.subplots(1, 2, figsize=(9, 7))
    
    #1st Subplot
    df.boxplot(column=['rate'], by='age', ax=axarray[0])
    
    #2nd Subplot
    df.boxplot(column=['rate'], by='age', ax=axarray[1])
    
    axarray[1].set_ylim(bottom=0, top=2)