简体   繁体   English

matplotlib-绘制错误的日期时间

[英]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. 我用matplotlib绘制了一个图,其中x轴带有带有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. 我在datetime64(熊猫系列)中有ts,并且还要显示(右)分钟和秒,所以我使用date2num遵循了此链接中的提示。 The problem is that it plots no-sense dates: 问题在于它绘制了无意义的日期: 在此处输入图片说明

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: df.toPandas()[“ timestamp”]是:

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. 我尝试将datetime64转换为datetime,但结果没有改变。

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. 当然,可以根据需要配置每个刻度的位置和名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM