2

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.

2
  • 1
    Can you post some code that reproduces this problem? see MCVE? Commented Feb 5, 2016 at 13:11
  • Why do you think the tick labels are wrong? The ticks are evenly spaced, not placed. If you want to control exactly where the ticks are placed, use ad FixedLocator for the xaxis major locator. Commented Feb 5, 2016 at 14:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.