python - 无法使用 Matplotlib 和 pandas 在 x 轴上显示“分钟:秒”
问题描述
我在使用 Matplotlib 和 pandas 数据框时遇到了一些问题。
我想根据测试开始后经过的时间绘制数据,并在 X 轴上显示“分钟:秒”。
为此,我将当前时间戳缩回第一个数据的时间戳,这给了我一个 timedelta64 对象。当我尝试打印时,使用正确的“小时:分钟:秒”表示。
但是当我尝试绘制图形时,X 轴完全是空的......
在下面的示例中,第一个图显示了 2000 万个刻度的分钟数。第二个是空的。
知道为什么这个轴是空的吗?
这是我的示例代码:
# Imports
import pandas as pd
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as tk
# Data creation
l = [random.randrange(0, 10) for i in range(100)]
d = []
for i in range(100):
d.append(datetime.datetime(2019, 12, 3, 11, 11, random.randrange(0, 60), 0) + datetime.timedelta(minutes=i))
df = pd.DataFrame()
df['time'] = d
df['value'] = l
df['reltime'] = df.time.apply(lambda x: x - df.time.iloc[0])
df.head(5)
df['reltime_s'] = df.reltime.apply(lambda x: x.total_seconds())
df['reltime_mn'] = df.reltime_s.apply(lambda x: x / 60)
df.head(5)
# Plotting
fig, ax = plt.subplots()
df.plot(x='reltime_mn', y='value', figsize=(18, 5), ax=ax)
plt.show()
fig, ax = plt.subplots()
df.plot(x='reltime', y='value', figsize=(18, 5), ax=ax)
plt.show()
解决方案
推荐阅读
- javascript - 类和数组作为参数
- python - 如何打印列表中所有元素的第一个字母?
- javascript - 突出显示活跃的“药丸”
- c# - 使用 C# 更新 JSON 文件中存在的特定项目
- c - 试图让 UART 在 dsPIC33EV256GM102 上工作
- c# - 在服务器上处理的小型 API 调用与存储在内存中的大型数据拉取
- pytorch - PyTorch 错误张量 a (128) 的大小必须与非单维 0 处的张量 b (9) 的大小相匹配
- xcode - 是否有一个键盘快捷键可以在 Xcode 中最近访问的两个选项卡之间切换?
- angular - 如果我使用此代码是否可以安全地抵御 XSS 攻击?
- java - 清除文件后如何继续写入文件?