0

I am trying to plot a graph that has dates (I want years and months as x-ticks). But when I try to plot the graph I either get the correct ticks but no graph showing (this is when I have ax.plot()... at the end) or the graph showing but getting the error (Failed to convert value(s) to axis units: numpy.datetime64('2020')). I don't know how to fix this. This is my piece of code:

years = mdates.YearLocator()
months = mdates.MonthLocator()
years_fmt = mdates.DateFormatter('%Y')



fig, ax = plt.subplots(1,1, figsize = (10,10))
ax.plot(Date_of_report, Total_reported)
#format ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_minor_locator(months)

#round nearest years
datemin = np.datetime64(Date_of_report[0], 'Y')
datemax = np.datetime64(Date_of_report[-1], 'Y') + np.timedelta64(1, 'Y')
ax.set_xlim(datemin, datemax)


ax.format_xdata = mdates.DateFormatter('%Y-%d-%m')
ax.grid(True)
fig.autofmt_xdate()
fig.show()
NANnl
  • 13
  • 3

1 Answers1

0

I've found the solution. When importing the data I imported the dates as string. Instead I imported it as dtype='datetime64[ns]'

np.loadtxt('/content/gdrive/MyDrive/corono/COVID-19_uitgevoerde_testen.csv',\
                       delimiter =';',skiprows=1, usecols=2, dtype='datetime64[ns]')
NANnl
  • 13
  • 3