【问题标题】:Changing the formatting of a datetime.time axis in matplotlib在 matplotlib 中更改 datetime.time 轴的格式
【发布时间】:2020-02-14 17:03:23
【问题描述】:

我正在尝试将 x 轴的格式更改为 %H:%M,而 xticklabel 全部变为 00:00。 xs 如下所示:

[datetime.time(15, 8, 35), datetime.time(15, 8, 36), datetime.time(15, 8, 37)]

我尝试了以下脚本:

import matplotlib.dates as mdate
import matplotlib.pyplot as plt

dates = ['15:08:35', '15:08:36', '15:08:37']
xs = [datetime.strptime(d, '%H:%M:%S').time() for d in dates]
ys = range(len(xs))

plt.gca().xaxis.set_major_formatter(mdate.DateFormatter('%H:%M'))
plt.gca().xaxis.set_major_locator(mdate.DayLocator())

# Plot
plt.plot(xs, ys)
plt.gcf().autofmt_xdate()
plt.show()

图像看起来像这样: Please click

如何将 xticklabel 更改为我想要的格式?

【问题讨论】:

    标签: python datetime matplotlib


    【解决方案1】:

    Matplotlib 比 time 对象更容易处理 datetime-objects。您可以删除.time()。这段代码应该可以工作,我编辑了日期以显示轴上不断变化的 x 值。

    import matplotlib.dates as mdate
    import matplotlib.pyplot as plt
    from datetime import datetime, timedelta
    
    dates = ["15:05:35", "16:08:36", "17:09:37"]
    # remove .time() from strptime
    xs = [datetime.strptime(d, "%H:%M:%S") for d in dates]
    
    ys = range(len(xs))
    
    plt.gca().xaxis.set_major_formatter(mdate.DateFormatter("%H:%M"))
    plt.gca().xaxis.set_major_locator(mdate.DayLocator())
    
    # show all x-values on the x-axis
    plt.xticks(xs)
    # Plot
    plt.plot(xs, ys)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      相关资源
      最近更新 更多