Matplotlib plot disappears upon adding annotation

Question:

I am trying to add some annotations to a graph I’ve made, however the entire plot disappears every time I try to add an annotation using the code:

ax.annotate(text='Hi', xy=(1-4-2020, 0), xycoords='data') 

Regardless of whether I change the co-ordinates, the same issue occurs.

Here is the plot I am using:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

plt.figure(figsize=[15, 10])
plt.grid(True)
plt.plot(tweets_df['date'], tweets_df['compoundSMA'])
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.gcf().autofmt_xdate()
#plt.savefig('sentimentSMAvaderhighqualitytest.png', dpi=300)
plt.show()

Any help or insight would be amazing.

Thanks.

Asked By: Albie

||

Answers:

xy=(1-4-2020, 0) works only when you’re plotting using Pandas. When using matplotlib, you’ll have to try this way

ax.annotate(text='Hi', xy=(mdates.date2num(dt.datetime(2020,4,1)), 0), xycoords='data')
Answered By: Krishnakanth Allika

try doing:

plt.waitforbuttonpress(-1)
Answered By: Márcio Ngolo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.