I have code that generates a large volume of daily charts, one each date in a list of dates. Previously I have simply called "fig, ax = plt.figure()" before iterating the dates and at the end of each iteration I clear the figure using "plt.cla()" and this has worked ok.
Recently I have added a secondary Y axis using ax2.twinx() and the previous method is not giving the desired results. The first iteration is ok, but the subsequent charts have artifacts of the chart before (imaged) https://imgur.com/IiFMV0N . As you can see the edges of the blue bars and also the secondary Y axis ticks remain.
I have been trying different combinations of .cla, .clf .remove, .clear without any success.
fig, ax = plt.subplots(figsize=(12,6), dpi=150)
font = {
'color': 'black',
'weight': 'bold',
'size': 12,
}
font_axis = {
'color': 'black',
'weight': 'normal',
'size': 12,
}
# Iterate though dates
for missing_date in missing_dates:
ax.set_facecolor('#f8f8ff')
ax2 = ax.twinx()
# Open csv file and filter for relevant data
count_path = f'{daily_counts_dir}/rCryptoCurrency_Counts_{missing_date}_top_100_day.csv'
df_count = pd.read_csv(open(count_path, 'r', encoding='utf-8'), sep=',')
df_count = df_count[df_count.sentiment_mean >= 0]
df_count.sort_values(by='count', ascending=False, inplace=True)
df_count = df_count.head(12)
labels = list(df_count.symbol.values)
counts = list(df_count['count'].values)
sent = list(df_count['sentiment_mean'].values)
x = np.arange(len(labels))
width = 0.3
rects1 = ax.bar(x - width/2, counts, width, label='Mentions', color='#3460af', edgecolor='black')
rects2 = ax2.bar(x + width/2, sent, width, label='Av. Sentiment', color='#df2e6d', edgecolor='black')
# Add some text for labels, title and custom x-axis tick labels, etc.
fmt_date = lambda x: dt.strftime(pd.to_datetime(x), '%d %b %Y')
ax.set_ylabel('Mentions', fontdict=font_axis)
ax2.set_ylabel('Average Sentiment', fontdict=font_axis)
ax.set_title(f'Currency Mentions & Average Sentiment Score\nFrom r/CryptoCurrency On {fmt_date(missing_date)}', fontdict=font)
ax.set_xticks(x)
ax.set_xticklabels(labels, fontdict=font)
ax.tick_params(axis="x", rotation=50)
plots = [rects1, rects2]
ax.legend(plots, ['Mentions', 'Av. Sentiments'])
ax2.set_ylim(0, 100)
fig.tight_layout()
# Save figure
save_path = f'{daily_charts_dir}/rCryptoCurrency_{missing_date}_top_100_day.png'
plt.savefig(fname=save_path, dpi=150)
plt.cla()