Che*_*eng 7 python datetime matplotlib pandas
比较以下代码:
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()
Run Code Online (Sandbox Code Playgroud)
我最后补充说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\n\n%a')) ## Added this line
Run Code Online (Sandbox Code Playgroud)
与第二张图的问题是,它开始于5-24代替5-25.此外,5-252017年是星期四而不是星期一.是什么导致了这个问题?这个时区有关系吗?(我不明白为什么日期数字叠加在一起)
Imp*_*est 10
通常,pandas和matplotlib的日期时间实用程序是不兼容的.因此,尝试在使用matplotlib.datespandas创建的日期轴上使用对象将在大多数情况下失败.
例如,从文档中可以看出一个原因
datetime对象转换为浮点数,表示自0001-01-01 UTC以来的天数加1.例如,0001-01-01,06:00是1.25,而不是0.25.
但是,这不是唯一的区别,因此建议在日期时间对象中不要混合使用pandas和matplotlib.
但是可以选择告诉大熊猫不要使用自己的日期时间格式.在那种情况下,使用matplotlib.dates代码是可能的.这可以通过引导.
df.plot(x_compat=True)
Run Code Online (Sandbox Code Playgroud)
由于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\n\n%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\n\n%a'))
plt.gca().invert_xaxis()
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8435 次 |
| 最近记录: |