【问题标题】:Display only time on axis with matplotlib.plot_dates使用 matplotlib.plot_dates 仅在轴上显示时间
【发布时间】:2021-12-30 13:19:07
【问题描述】:

所以我花了一些时间来管理在 x 轴上使用时间绘制数据,我发现这样做的方法是在将 datetime 对象转换为 pltdates 对象后使用 matplotlib.plot_date。

X_d = pltdates.date2num(X) # X is an array containing datetime objects
(...)
plt.plot_date(X_d, Y)

效果很好,我的所有数据都绘制正确。

Plot with dates appearing on x-axis

但是,我要绘制的所有度量都是在同一天(2021 年 12 月 17 日)进行的,唯一的区别是时间。

如图所示,matplotlib 仍然显示当天(第 17 天)的数字,尽管它在整个图中是相同的。

任何人都知道如何只保留时间,仍在使用 matplotlib.plot_date?

【问题讨论】:

  • 你可以试试plt.gca().xaxis.set_major_formatter(matplotlib.ticker.DateFormatter('%H:%M'))。另请参阅this old tutorial example
  • 非常感谢,它确实解决了我的问题!!你发给我的链接很有趣,如果我以后花更多时间在 Python 上制作图表,我可能会更深入地了解。

标签: python date matplotlib time


【解决方案1】:

使用这个例子:

import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime

origin = ['2020-02-05 04:11:55',
          '2020-02-05 05:01:51',
          '2020-02-05 07:44:49']

a = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in origin]
b = ['35.764299', '20.3008', '36.94704']
x = matplotlib.dates.date2num(a)

formatter = matplotlib.dates.DateFormatter('%H:%M')

figure = plt.figure()
axes = figure.add_subplot(1, 1, 1)
axes.xaxis.set_major_formatter(formatter)
plt.setp(axes.get_xticklabels(), rotation=15)

axes.plot(x, b)
plt.show()

【讨论】:

  • 这实际上只允许显示时间,但是我没有自动设置 x 刻度(16:00、16:10 等)并在轴(16:11、16:27 等),我不想手动设置。上面 JohanC 的解决方案正是我想要的。还是谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-30
相关资源
最近更新 更多