【问题标题】:Python chart axis formatting doesn't work for subplotsPython 图表轴格式不适用于子图
【发布时间】:2018-04-23 01:47:05
【问题描述】:

我有一个 pandas 数据框,其索引为从 DatetimeIndex 派生的 datetime.time 对象,

In: df.index
Out: 
Index([00:00:00, 00:30:00, 01:00:00, 01:30:00, 02:00:00, 02:30:00, 03:00:00,
       03:30:00, 04:00:00, 04:30:00, 05:00:00, 05:30:00, 06:00:00, 06:30:00,
       07:00:00, 07:30:00, 08:00:00, 08:30:00, 09:00:00, 09:30:00, 10:00:00,
       10:30:00, 11:00:00, 11:30:00, 12:00:00, 12:30:00, 13:00:00, 13:30:00,
       14:00:00, 14:30:00, 15:00:00, 15:30:00, 16:00:00, 16:30:00, 17:00:00,
       17:30:00, 18:00:00, 18:30:00, 19:00:00, 19:30:00, 20:00:00, 20:30:00,
       21:00:00, 21:30:00, 22:00:00, 22:30:00, 23:00:00, 23:30:00],
      dtype='object')

我正在从 df 绘制图表:

import matplotlib.pyplot as plt
fig,ax = plt.subplot
ax.plot(df.index, df,  marker='', linestyle='solid',linewidth=1, alpha=1)

我想将 x 轴格式化为每 4 小时有一次刻度标签

使用matplotlib.dates

import matplotlib.dates as md
ax.xaxis.set_major_locator(md.HourLocator(interval=4))
ax.xaxis.set_major_formatter(md.DateFormatter('%H'))

没有效果,因为索引不是DatetimeIndex,那么我用什么来格式化轴呢?

【问题讨论】:

  • 我想答案很简单:使用 datetime 对象作为索引或至少使用 datetime 对象作为 x 值进行绘图。
  • 好的,如何在不添加虚假数据信息的情况下将datetime.time对象转换为datetime
  • 只需选择 1900 年 1 月 1 日或任何您喜欢的日期。

标签: python pandas matplotlib time formatter


【解决方案1】:

正如@ImportanceofBeingErnest 所建议的,答案是将索引中的datetime.time 对象改回“日期时间”对象以恢复DatetimeIndex

import datetime as dt   
random_date = dt.date(1901, 1, 1)
df.index = pd.DatetimeIndex([dt.datetime.combine(random_date, t) for t in df.index])

【讨论】:

    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2011-12-03
    相关资源
    最近更新 更多