Home > Software engineering >  Python: Datetime dates plotted repeatedly
Python: Datetime dates plotted repeatedly

Time:03-20

I have three datetime.date() objects and three points and the first and second date appear four times as x-ticks. Why? How can I prevent that?

import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dates = [datetime.date(2022, 3, 17), datetime.date(2022, 3, 18), datetime.date(2022, 3, 19)]
b = (0,1,2)

plt.errorbar(dates, b, fmt = '.')

myFmt = mdates.DateFormatter('%d-%m-%y')    
plt.gca().xaxis.set_major_formatter(myFmt)
plt.xticks(rotation=30)

plt.show()

Edit: Solved.

As Inquirer answered, if you only want to plot the dates you have, solution is:

plt.xticks(ticks = dates)

if you want to have only every other day, I found now:

ax = plt.axes()
...
ax.xaxis.set_major_locator(mdates.DayLocator(interval = 1))

CodePudding user response:

import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dates = [datetime.date(2022, 3, 17), datetime.date(2022, 3, 18), datetime.date(2022, 3, 19)]
b = (0,1,2)

plt.errorbar(dates, b, fmt = '.')

myFmt = mdates.DateFormatter('%d-%m-%y')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.xticks(ticks=dates )

plt.show()
  • Related