Search code examples
pythonpandasplotautocorrelation

Plotting multiple Pandas autocorrelation plots in different plots


My question is somewhat related to this one. I have a Pandas DataFrame and I want to separately plot the autocorrelation function for value each item in category. Below is what I've tried, and it plots all of the autocorrelation functions on the same plot. How can I plot them separately and also control plot size?

# Import libraries
import pandas as pd
from pandas.plotting import autocorrelation_plot

# Create DataFrame
df = pd.DataFrame({
    'category': ['sav','sav','sav','sav','sav','check','check','check','check','check','cd','cd','cd','cd','cd'],
    'value': [1.2,1.3,1.5,1.7,1.8, 10,13,17,20,25, 7,8,8.5,9,9.3]
})

# Loop through for each item in category and plot autocorrelation function
for cat in df['category'].unique():
    s = df[df['category']==cat]['value']
    s = s.diff().iloc[1:] #First order difference to de-trend
    ax = autocorrelation_plot(s)

enter image description here


Solution

  • One easy way is to force rendering after each iteration with plt.show():

    # Loop through for each item in category and plot autocorrelation function
    for cat in df['category'].unique():
    
        # create new figure, play with size
        plt.figure(figsize=(10,6))
        s = df[df['category']==cat]['value']
        s = s.diff().iloc[1:] #First order difference to de-trend
        ax = autocorrelation_plot(s)
        plt.show()  # here
    

    Also the syntax can be simplified with groupby:

    for cat, data in df.groupby('category')['value']:
        plt.figure(figsize=(10,6))
    
        autocorrelation_plot(data.diff().iloc[1:])
    
        plt.title(cat)
        plt.show()