首页 > 解决方案 > 无法使用 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()

标签: pythonpandasmatplotlib

解决方案


推荐阅读