Pandas Dataframe 线图在 xaxis 上显示日期
- 2025-01-16 08:38:00
- admin 原创
- 151
问题描述:
比较以下代码:
test = pd.DataFrame({'date':['20170527','20170526','20170525'],'ratio1':[1,0.98,0.97]})
test['date'] = pd.to_datetime(test['date'])
test = test.set_index('date')
ax = test.plot()
我DateFormatter
最后补充道:
test = pd.DataFrame({'date':['20170527','20170526','20170525'],'ratio1':[1,0.98,0.97]})
test['date'] = pd.to_datetime(test['date'])
test = test.set_index('date')
ax = test.plot()
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d
%a')) ## Added this line
第二张图的问题在于它从 开始,5-24
而不是5-25
。另外,5-25
2017 年的 是星期四,而不是星期一。是什么导致了这个问题?这与时区有关吗?(我也不明白为什么日期数字会堆叠在一起)
解决方案 1:
一般来说,pandas 和 matplotlib 的日期时间实用程序不兼容。因此,尝试在matplotlib.dates
用 pandas 创建的日期轴上使用对象在大多数情况下都会失败。
其中一个原因是从文档中可以看出
datetime
对象被转换为浮点数,表示自 0001-01-01 UTC 以来的天数加 1。例如,0001-01-01, 06:00 是 1.25,而不是 0.25。
然而,这并不是唯一的区别,因此建议在涉及日期时间对象时不要混合 pandas 和 matplotlib。
但是,有一个选项可以告诉 pandas 不要使用其自己的日期时间格式。在这种情况下,matplotlib.dates
可以使用代码。这可以通过以下方式进行控制。
df.plot(x_compat=True)
由于 pandas 没有提供复杂的日期格式化功能,因此可以使用 matplotlib 进行绘图和格式化。
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
df = pd.DataFrame({'date':['20170527','20170526','20170525'],'ratio1':[1,0.98,0.97]})
df['date'] = pd.to_datetime(df['date'])
usePandas=True
#Either use pandas
if usePandas:
df = df.set_index('date')
df.plot(x_compat=True)
plt.gca().xaxis.set_major_locator(dates.DayLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d
%a'))
plt.gca().invert_xaxis()
plt.gcf().autofmt_xdate(rotation=0, ha="center")
# or use matplotlib
else:
plt.plot(df["date"], df["ratio1"])
plt.gca().xaxis.set_major_locator(dates.DayLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d
%a'))
plt.gca().invert_xaxis()
plt.show()
使用 matplotlib 面向对象 API 进行更新
usePandas=True
#Either use pandas
if usePandas:
df = df.set_index('date')
ax = df.plot(x_compat=True, figsize=(6, 4))
ax.xaxis.set_major_locator(dates.DayLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('%d
%a'))
ax.invert_xaxis()
ax.get_figure().autofmt_xdate(rotation=0, ha="center")
# or use matplotlib
else:
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot('date', 'ratio1', data=df)
ax.xaxis.set_major_locator(dates.DayLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('%d
%a'))
fig.invert_xaxis()
plt.show()
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD