0

I am graphing the results of the measurements of a humidity sensor over time. I'm using Python 3.7.1 and Pandas 0.24.2.

I have a list called dateTimeList with date and time strings:

dateTimeList = ['15.3.2019 11:44:27', '15.3.2019 12:44:33', '15.3.2019 13:44:39']

I wrote this code where index is a DatetimeIndex object and humList is a list of floats.

    index = pd.to_datetime(dateTimeList, format='%d.%m.%Y %H:%M:%S')
    ts = pd.Series(humList, index)

    plt.figure(figsize=(12.80, 7.20))
    ts.plot(title='Gráfico de Humedad en el Tiempo', style='g', marker='o')

    plt.xlabel('Tiempo [días]')
    plt.ylabel('Humedad [V]')
    plt.grid()
    plt.savefig('Hum_General'+'.png', bbox_inches='tight')
    plt.show()

And I have this two results, one with data from February1 and the other one with data from March2.

The problem is that in March instead of leaving the year 2019, sequences of 00 12 00 12 appear on the x axis. I think it is important to note that this only happens on the data of March, since February is ok, and the data of both months have the same structure. Day and Month are shown correctly on both plots.

I also tried with:

index = [ pd.to_datetime(date, format='%d.%m.%Y %H:%M:%S') for date in dateTimeList]

Now index is a list of Timestamps objects. Same Results.

1 Answers1

0

Add this immediately after creating the plot

import matplotlib.dates as mdates  # this should be on the top of the script
xfmt = mdates.DateFormatter('%Y-%m-%d')
ax = plt.gca()
ax.xaxis.set_major_formatter(xfmt)

My guess is that since March has less data points, Matplotlib prefers to label dates as month-day-hour instead of year-month-date, so probably when you have more data in March the issue should fix itself. The code I posted should keep a year-month-day format regardless the number of data points used to plot.

Canas
  • 31
  • 3