【问题标题】:pandas plot with timestamps on x axis - tick units?熊猫在x轴上绘制时间戳 - 刻度单位?
【发布时间】:2019-04-20 14:23:41
【问题描述】:

我有一个带有日期时间值的 pandas 数据框:

    Date/Time           Event Value
0   2018-11-15 17:17:49 62
1   2018-11-15 17:27:50 63
2   2018-11-15 17:37:50 64
3   2018-11-15 17:42:49 65
4   2018-11-15 18:17:49 64
5   2018-11-15 19:27:48 65
6   2018-11-15 19:37:48 66
7   2018-11-15 19:47:49 67
8   2018-11-15 19:57:49 68
9   2018-11-15 20:12:49 69

print (tmp.dtypes)

Date/Time      datetime64[ns]
Event Value             int64

图表如下所示:

fig, ax1 = plt.subplots(1,1,figsize=(8,4))
tmp.plot(x='Date/Time',y='Event Value', legend=None, ax=ax1)

x 轴已用适当的日期和时间格式化(并且可以使用set_major_formatter 进一步格式化)。

现在我想在图表上绘制一个矩形,以突出显示特定时间。为此,我需要知道 x 位置。

print([x for x in ax1.get_xticks()])

[737013.7291666666, 737013.75, 737013.7708333334, 737013.7916666666, 737013.8125, 737013.8333333334]

这些确实是 x 值,即如果我将它们用作它按预期绘制的矩形的原点。

rect = patches.Rectangle((737013.75,55),.01,100)
ax1.add_patch(rect)

我不明白这些数字是从哪里来的。它们不是纪元值,尽管它们看起来有点像('737013.75' 对应于 '1970-01-09 07:43:33',这对我来说没有任何意义)。

如何从数据框中的日期/时间值获取图表上的 x 位置?

【问题讨论】:

    标签: python pandas datetime matplotlib


    【解决方案1】:

    如果您使用 x_compat=True 选项绘制数据框,您可以确定单位是 matplotlib.dates 单位。否则,熊猫可能会为您决定一些单位。

    在这里,pandas 使用 matplotlib 日期单位。他们是defined as:

    Matplotlib 使用浮点数表示日期,指定自 0001-01-01 UTC 以来的天数加 1。例如,0001-01-01, 06:00 是 1.25,而不是 0.25。值

    但是,您不需要自己计算这些单位。 Matplotlib 提供辅助函数

    • matplotlib.dates.date2num
    • matplotlib.dates.num2date
    • matplotlib.dates.datestr2num

    您可以使用它在单位之间来回计算。

    例如,matplotlib.dates.datestr2num("2018-11-15 19:27:48") 为您提供737013.8109722222。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 2020-09-28
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 2020-07-29
      相关资源
      最近更新 更多