【问题标题】:plotting millisecond timestamp against data does not align well in python在 python 中针对数据绘制毫秒时间戳并不能很好地对齐
【发布时间】:2020-09-13 04:40:59
【问题描述】:

我想通过相互绘制来显示时间戳和数据之间的关系。互联网上有很多例子,但它似乎没有给我我正在寻找的答案。以下是我的示例数据

timestamp           data 
2020-05-19 10:13:31.6     -73.2031
2020-05-19 10:13:31.7     -87.8437
2020-05-19 10:13:31.8     -87.8437
2020-05-19 10:13:31.9     -87.8437
2020-05-19 10:13:32       -87.8437
2020-05-19 10:13:32.1     -87.8437
2020-05-19 10:13:32.2     -87.8437
2020-05-19 10:13:32.3     -87.8437
2020-05-19 10:13:32.4     -87.8437
2020-05-19 10:13:32.5     -87.8437
2020-05-19 10:13:32.6     -87.8437
2020-05-19 10:13:32.7     -87.8437
2020-05-19 10:13:32.8     -87.8437
......................

2020-05-19 10:19:15.2    -92.4709 
2020-05-19 10:19:15.3    -99.9328
2020-05-19 10:19:15.4   -110.0390
2020-05-19 10:19:15.5   -118.0167
2020-05-19 10:19:15.6   -124.4937
2020-05-19 10:19:15.7   -128.2135
2020-05-19 10:19:15.8   -134.1289
2020-05-19 10:19:15.9   -138.6015
2020-05-19 10:19:16     -142.3212
2020-05-19 10:19:16.1   -146.6750
2020-05-19 10:19:16.2   -153.4466

下面是我的python代码:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

df.index = pd.to_datetime(df.timestamp,format="%Y.%m.%d %H:%M:%S.%f", dayfirst=True)
y=df['data']

fig, ax = plt.subplots(figsize=(50, 3)) #tired to increase the size,to cover all timestamps
ax = y.plot(color='xkcd:lightish blue')

plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)

df.set_index('timestamp',inplace=True)
ticklabels = df.index.strftime('%Y.%m.%d %H:%M:%OS3')
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.show()

我得到的情节并没有给我所有的时间戳。从图中可以看出,即使是近似的时间戳也不与数据对齐:(例如,我的时间戳一直到 2020-05-19 10:19:16.2 但该图从 10:13:31 开始显示: 600 到 10:13:32:100)

我应该怎么做才能对齐数据?我做错了吗? 如果是这样,根据数据绘制时间戳的最佳方法是什么?我不介意使用 seaborn 等其他库

谢谢

【问题讨论】:

  • 只需删除ax.xaxis.set_major_formatter 行。
  • 当我删除该行时,我只看到 19 10:、19 10:15、19 10:16。这不会以毫秒为单位显示时间戳。此外,显示部分时间戳
  • ax.xaxis.set_major_formatter 似乎也是我的问题。

标签: python pandas matplotlib plotly seaborn


【解决方案1】:

Matplotlib 的 DateFormatter 在这里可能很有用。它将使用strftime 格式字符串格式化刻度。

所以是这样的:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

import matplotlib.dates as mdates

df=pd.read_csv('time.csv',index_col='timestamp') #your data pasted into csv
df.index = pd.to_datetime(df.index)

df.index = pd.to_datetime(df.index,format="%Y.%m.%d %H:%M:%S.%f", dayfirst=True)
y=df['data']

fig, ax = plt.subplots(figsize=(9, 9))
ax = y.plot(color='xkcd:lightish blue',marker='x')

plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y.%m.%d %H:%M:%S.%f'))

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    相关资源
    最近更新 更多