Plotting with matplotlib does not give the desired date and time format

The data I use is produced from an excel file using pd.read_excel.

Purpose: to display DateTime vs Value with x-axis values ​​in format %Y-%m-%d %H:%M:%S.

Problem: X axis format is not desired %Y-%m-%d %H:%M:%S.

Below is the code snippet that I used and its result. I am very new to programming in general and will be very grateful if you guys can point me in the right direction!

>>> df.head()

            DateTime  Value
0 2016-05-17 22:50:27   1914
1 2016-05-17 22:55:27   1597
2 2016-05-17 23:00:27   1429
3 2016-05-17 23:05:27   1462
4 2016-05-17 23:10:27   2038

>>> df['DateTime'] = pd.to_datetime(df['DateTime'], format='%Y-%m-%d %H:%M:%S')

>>> df.plot(x='DateTime', y='Value')

>>> plt.show()

The plot of DateTime vs Value:
Plot of DateTime vs Value

+4
source share
1 answer

You can use matplotlib.dates.DateFormatterto achieve this:

import matplotlib.dates as dates
df['DateTime'] = pd.to_datetime(df['DateTime'], format='%Y-%m-%d %H:%M:%S')
df.plot(x='DateTime', y='Value')
formatter = dates.DateFormatter('%Y-%m-%d %H:%M:%S') 
plt.gcf().axes[0].xaxis.set_major_formatter(formatter)

:

enter image description here

to_datetime datetime64 dtype, pandas matplotlib, .

, dt.strftime, , , , :

In [39]:
df['DateStrings'] = df['DateTime'].dt.strftime('%Y-%m-%d %H:%M:%S')
df

Out[39]:
             DateTime  Value          DateStrings
0 2016-05-17 22:50:27   1914  2016-05-17 22:50:27
1 2016-05-17 22:55:27   1597  2016-05-17 22:55:27
2 2016-05-17 23:00:27   1429  2016-05-17 23:00:27
3 2016-05-17 23:05:27   1462  2016-05-17 23:05:27
4 2016-05-17 23:10:27   2038  2016-05-17 23:10:27

:

df.plot(x='DateStrings', y='Value')
plt.show()

enter image description here

, X- duff, ,

+3

Source: https://habr.com/ru/post/1672336/


All Articles