user2523485
user2523485

Reputation:

matplotlib - plot wrong datetime

I'd plot a figure with matplotlib in which the x-axis there are timestamp with yy-mm-dd hh-mm-ss. I have ts in datetime64 (pandas series) and to show also (right) minutes and seconds i follow the hint in this link using date2num. The problem is that it plots no-sense dates:enter image description here

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as md   
for df in dfs:
    datenums=md.date2num(df.toPandas()["timestamp"])
    plt.xticks(rotation=25)
    xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
    ax.xaxis.set_major_formatter(xfmt)
    plt.plot(datenums,x)
    plt.show()

where df.toPandas()["timestamp"] is:

0   2015-12-15 03:53:13
Name: timestamp, dtype: datetime64[ns]

I tried to convert datetime64 in datetime but the result doesn't change.

Upvotes: 2

Views: 3177

Answers (1)

iblasi
iblasi

Reputation: 1307

If you have your timestamp values on seconds, use this to create a list for all the tick labels and then add them to the plot considering your data is related to an array of timestamps

import matplotlib.pyplot as plt
import numpy as np
import datetime

OX_ticks_name = [datetime.datetime.fromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S') for x in arrayTmstmp]
OX_ticks_pos = np.arange(0,len(arrayTmstmp))

fig, ax = plt.subplots(figsize=(16, 9), dpi=100)
...
ax.set_xticks(OX_ticks_pos)
ax.set_xticklabels(OX_ticks_name, rotation=40, horizontalalignment='right', fontsize=10)
plt.tight_layout()
plt.show()

Of course, the position of each tick and the name for each can be configured as you want.

Upvotes: 1

Related Questions