2

I'm trying to plot my dataframe using matplotlib.pyplot. I'm plotting a total of 5k plots and midway the kernel dies.

enter image description here

You can use this code to generate this simple dataframe:

import pandas as pd
import numpy as np

df=pd.DataFrame()
countries = ['Argentina', 'Brazil', 'Chile', 'China', 'Colombia', 'Czech Republic', 'Egypt', 'Greece', 'United Arab Emirates']

for c in countries:
    df=df.append(pd.DataFrame({'date':pd.date_range(start='2001-01-01',end='2021-12-31',freq='B'),'country':c}))

df['value'] = np.random.randint(0,100,len(df))
df

Next, I'm trying to plot the value and country for each particular date.

for d in list(df.date.unique()):         # For each unique date, make a plot
    ax=(df.loc[df.date==d,['country','value']].set_index('country').sort_values('value')
        .plot())
    print(f'{d} done.')
    del ax

How can I resolve this issue?

Prats
  • 649
  • 2
  • 15
  • I have also seen this warning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. Maybe using another graphing tool might solve your issue. – Batselot Apr 12 '22 at 08:56
  • Checking in again. Your code runs just fine on my vs code jupyter extension except the part that took like a lot of time to generate the graphs. – Batselot Apr 12 '22 at 11:25
  • Apologies for the late reply. I'm using jupyter with 64GB memory but it seems to be crashing after plotting around 600 plots. How can I clear the memory after each plot? – Prats Apr 14 '22 at 06:26
  • No worries. I think the bountied answer in here can help you out. Would you mind checking it out if that works out for you? https://stackoverflow.com/questions/28757348/how-to-clear-memory-completely-of-all-matplotlib-plots – Batselot Apr 14 '22 at 07:03
  • 1
    Thanks. I've tried that and it works as well. Also found out that the issue is because of defining `%matplotlib inline` in my jupyter notebook. Since, we plot it inline, it takes up some memory internally, couldn't find any fixed solution for that – Prats Apr 14 '22 at 07:14

0 Answers0