如何创建带有时间戳的散点图

How to create a scatter plot with timestamps

如何使用timestamps生成散点图?

下面是一个例子,但我得到一个错误ValueError: First argument must be a sequence

import pandas as pd
import matplotlib.pyplot as plt

d = ({
    'A' : ['08:00:00','08:10:00'],
    'B' : ['1','2'],           
    })

df = pd.DataFrame(data=d)

fig = plt.figure()

x = df['A']
y = df['B']

plt.scatter(x,y)

如果我将时间戳转换为总秒数,它会起作用:

df['A'] = pd.to_timedelta(df['A'], errors="coerce").dt.total_seconds()

但我希望 x 轴上显示 24 小时时间,而不是总秒数。

使用 x-ticks:

d = ({
'A' : ['08:00:00','08:10:00'],
'B' : [1,2],
})

df = pd.DataFrame(data=d)

fig = plt.figure()

x = df['A']
y = df['B']

x_numbers = list(pd.to_timedelta(df['A'], errors="coerce").dt.total_seconds ())
plt.scatter(x_numbers, y)
plt.xticks(x_numbers, x)
plt.show()

这会将时间戳绘制为 x 轴上的刻度线。

请注意,我将数据框中的 'B' 列转换为数字而不是字符串。如果它们确实需要是字符串或从文件中作为字符串导入,只需将它们转换为数字,例如通过 float()int().