首页 > 解决方案 > 为 matplotlib 转换时间戳以进行数据可视化

问题描述

我有带有时间戳的 ax 轴,y 轴有一些 int 值,提供了下面的值。我正在尝试使用 matplotlib 绘制具有 x 和 y 值的图形

我试过下面的代码,它不起作用。有人可以帮我解决这个问题吗

from datetime import datetime
from matplotlib.dates import date2num
import pandas as pd

X = []

for i in x:
    tim = datetime.strptime(i, '%Y-%m-%d %H:%M:%S.%f')
    dat = date2num(t)
    X.append(dat)

print(X)

from matplotlib import pyplot as plt

plt.plot(X,y)
plt.show()

并且还从堆栈溢出中尝试了以下代码

pyplot 轴中日期时间的格式

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(X, y)

# format your data to desired format. Here I chose YYYY-MM-DD but you can set it to whatever you want.
import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S.%f'))

# rotate and align the tick labels so they look better
fig.autofmt_xdate()

请在屏幕截图中找到输出

x = ['2020-04-26 19:28:40.136', '2020-04-26 19:28:39.970', '2020-04-26 19:28:37.670', '2020-04-26 19:27:46.196', '2020-04-26 19:27:45.852', '2020-04-26 19:27:43.740', '2020-04-26 19:27:13.641', '2020-04-26 19:26:22.070', '2020-04-26 19:26:19.783', '2020-04-26 19:02:50.721', '2020-04-26 19:02:49.504', '2020-04-26 19:02:49.192', '2020-04-26 18:57:47.572', '2020-04-26 18:14:26.204']

y = ['2', '2', '2', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0']

按照建议将 y 转换为 int 后。我能够绘制指标。但是,无法在指标中看到时间戳,如下所示

将 y 更改为 int 后的输出

标签: matplotlib

解决方案


推荐阅读