Search code examples
pythonplotstatsforecast

Can't get Statsforecast plot feature to display inside for loop


I don't seem to be able to get the statsforecast.StatsForecast.plot method to display inside for loops. A bug report may be more appropriate but this seems so basic (and I have seen similar code work elsewhere) that I believe I am missing something. There is a similar question here, but I believe the answer is not really acceptable. The goal is to visualise the cross_validation output from neuralforecast models (such as AutoNHITS), such as was done here with the cutoffs in step 5.

The following is a small reproducible example. The counter var has no impact on the dataframe and the method call works perfectly fine when outside the single iteration for loop. I also attempted to add plt.show() or similar commands to no avail.

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from statsforecast import StatsForecast

times_arr = np.arange(datetime(1985,7,1), datetime(1988,3,27), timedelta(days=1)).astype(datetime).tolist()
test_df = pd.DataFrame({
    'unique_id': ['a'] * 1000 + ['b'] * 1000,
    'ds': times_arr + times_arr,
    'y': np.random.random(2000)
})

for i in range(1):
    StatsForecast.plot(test_df)

Solution

  • The most concise answers seems to be shown in this issue on the statsforecast repo, by jmoralez

    from IPython.display import display
    
    for cutoff in cv_df['cutoff'].unique():
        fig = StatsForecast.plot(
            Y_df, 
            cv_df.query('cutoff == @cutoff').drop(columns=['y', 'cutoff']), 
            max_insample_length=48 * 4, 
            unique_ids=['H105'],
            engine='matplotlib'
        )
        display(fig)