【问题标题】:Matplotlib dateformatter is not formatting the date as wishedMatplotlib dateformatter 未按要求格式化日期
【发布时间】:2021-03-22 16:39:16
【问题描述】:

我有这个 pandas 数据框,我想通过只显示天、小时、分钟和秒来绘制它。

随着时间的推移,我有一个以毫秒为单位的 Unix 时间戳,我将其转换为您在数据框中已经看到的格式。

frm = mdates.DateFormatter('%Y-%m-%d %H:%M:%S')
df['startTime'] = pd.to_datetime((df['startTime']), unit='ms')
print(df)

plt.plot_date(df['startTime'], df['parameter.value'], linestyle='solid')
plt.gcf().autofmt_xdate()
plt.gca().xaxis.set_major_formatter(frm)

plt.show()

虽然我使用 DateFormatter 对其进行了格式化,但分钟和秒仍然没有出现在图中。

【问题讨论】:

  • 您能提供一个minimal reproducible example吗?这只是为了让任何回答的人都可以重现问题并能够更有效地诊断它。最好有一个示例,包括您的数据框是如何创建和格式化的。

标签: python pandas matplotlib pycharm dateformatter


【解决方案1】:

如果X轴是字符串,可以不四舍五入显示日期/时间格式。

import matplotlib.dates as mdates
import matplotlib.pyplot as plt

df['startTime'] = pd.to_datetime(df['startTime'], format='%Y-%m-%d %H:%M:%S.%f')
print(df)

plt.plot_date(df['startTime'].astype(str), df['parameter.value'], xdate=True, linestyle='solid')
# plt.gcf().autofmt_xdate()
# plt.gca().xaxis.set_major_formatter(frm)

plt.xticks(rotation=90)
plt.show()

【讨论】:

  • 这是一种变通方法,事实上我知道。我很惊讶为什么 DateFormatter 不适用于 %M:%S。但是,非常感谢您的努力。我标记了答案,但很遗憾我不能接受它作为解决方案。
  • SecondLocator(interval=3000) 这样做会以秒为单位显示,但间隔值会以3000秒为单位,这不符合您的目的,所以您选择了一个字符串。很抱歉没有达到您的期望。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
  • 2013-02-20
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
相关资源
最近更新 更多