'Matplotlib plots in the wrong data format eventhough it is a datetime object [duplicate]

I have a problem when trying to plot a timeseries with matplotlib:

df = pd.read_csv('myfile.dat', skiprows=1)

#Change data type to datetime
date_format = '%Y-%m-%d %H:%M:%S'
df['TIME'] = pd.to_datetime(df['TIME'], format=date_format)

fig, ax = plt.subplots()
ax.plot(df['TIME'], df['Value'])
plt.show()

If I do:

print(df['TIME'][0])

the output is:

2022-04-16 14:32:00

which is the correct format! But when I plot everything, it changes to:

enter image description here

Can someone help me? I saw several times that you actually do not need Formatter and all that stuff.



Solution 1:[1]

Matplotlib finds the best format according to your date. For example if there were only data per each hour of a day, it would display just the hours, if data there were only a data per day during a span of a week, it would display just the days.

The solution I propose is with mdates.DateFormatter:

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

df = pd.read_csv('file.csv')
print (df)

#Change data type to datetime
date_format = '%Y-%m-%d %H:%M:%S'
df['TIME'] = pd.to_datetime(df['TIME'], format=date_format)

fig, ax = plt.subplots()
ax.plot(df['TIME'], df['Value'])
plt.xticks(rotation=45, ha='right')
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
plt.show()

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1