如何在散点图的 x 轴上绘制每分钟的时间

Chu*_*uHo 3 python datetime matplotlib pandas x-axis

为 1 秒采样数据设置分钟小刻度:OverflowError: int too big to convert

考虑这个数据帧,采样间隔为 1 秒,持续时间约为 30 分钟:

import matplotlib.pyplot as plt
from matplotlib.dates import MinuteLocator
import pandas as pd

ndex = pd.date_range('2021-08-01 07:07:07', '2021-08-01 07:41:12', freq='1S', name='Time') 
df = pd.DataFrame(data=np.random.randint(1, 100, len(ndex)), index=ndex, columns=['A'])
Run Code Online (Sandbox Code Playgroud)

现在我们绘制它:

fig, ax = plt.subplots()
df.plot(color='red', marker='x', lw=0, ms=0.2, ax=ax)
Run Code Online (Sandbox Code Playgroud)

这创造了一个没有任何抱怨的情节: 时间与兰特

现在我希望每分钟都有轻微的滴答声。

我试过这个:

ax.xaxis.set_minor_locator(MinuteLocator())
Run Code Online (Sandbox Code Playgroud)

但这失败了OverflowError: int too big to convert

Tre*_*ney 5

  • pandas.DataFrame.plot用作matplotlib默认的绘图后端,但它将日期刻度编码为 un​​ix 时间戳,这会导致OverflowError: int too big to convert.
    • 这里的默认值是kind='line',但marker='x', lw=0, ms=0.2在 OP 中用于制作一个 hacky 散点图。
  • pandas.DataFrame.plot.scatter将正常工作。
  • 使用matplotlib.pyplot.scatter将按预期工作。
    • matplotlib:日期刻度标签
      • Matplotlib 日期绘图是通过将日期实例转换为自纪元以来的天数(默认为 1970-01-01T00:00:00)来完成的
  • seaborn.scatterplot也将工作:
    • sns.scatterplot(x=df.index, y=df.A, color='red', marker='x', ax=ax)
  • 测试于python 3.8.11, pandas 1.3.2, matplotlib 3.4.3,seaborn 0.11.2

matplotlib.pyplot.scatter

  • '01'额外的格式具有删除刻度标签中时间之前的月份 ( ) 的效果(例如'%m %H:%M')。
import matplotlib.dates as mdates
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(25, 6))
ax.scatter(x=df.index, y=df.A, color='red', marker='x')

hourlocator = mdates.HourLocator(interval=1)  # adds some extra formatting, but not required
majorFmt = mdates.DateFormatter('%H:%M')  # adds some extra formatting, but not required

ax.xaxis.set_major_locator(mdates.MinuteLocator())

ax.xaxis.set_major_formatter(majorFmt)  # adds some extra formatting, but not required
_ = plt.xticks(rotation=90)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

pandas.DataFrame.plot.scatter

  • pandas.DataFrame.plot带有kind='scatter'
    • ax = df.reset_index().plot(kind='scatter', x='Time', y='A', color='red', marker='x', figsize=(25, 6), rot=90)
# reset the index so Time will be a column to assign to x
ax = df.reset_index().plot.scatter(x='Time', y='A', color='red', marker='x', figsize=(25, 6), rot=90)
ax.xaxis.set_major_locator(mdates.MinuteLocator())
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


  • 注意两种方法产生的 xticks 的差异

pandas.DataFrame.plot xticks

ax = df.plot(color='red', marker='x', lw=0, ms=0.2, figsize=(25, 6))

# extract the xticks to see the format
ticks = ax.get_xticks()
print(ticks)
[out]:
array([1627801627, 1627803672], dtype=int64)

# convert the column to unix format to compare
(df.index - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')

[out]:
Int64Index([1627801627, 1627801628, 1627801629, 1627801630, 1627801631,
            1627801632, 1627801633, 1627801634, 1627801635, 1627801636,
            ...
            1627803663, 1627803664, 1627803665, 1627803666, 1627803667,
            1627803668, 1627803669, 1627803670, 1627803671, 1627803672],
           dtype='int64', name='Time', length=2046)
Run Code Online (Sandbox Code Playgroud)

matplotlib.pyplot.scatter xticks

fig, ax = plt.subplots(figsize=(25, 6))
ax.scatter(x=df.index, y=df.A, color='red', marker='x')

ticks2 = ax.get_xticks()
print(ticks2)

[out]:
array([18840.29861111, 18840.30208333, 18840.30555556, 18840.30902778,
       18840.3125    , 18840.31597222, 18840.31944444])
Run Code Online (Sandbox Code Playgroud)