在Pandas图上添加天数

时间:2015-12-18 13:51:46

标签: python pandas matplotlib plot

使用pandas绘制DataFrame时:

import pandas as pd
import matplotlib.pyplot as plt 
from StringIO import StringIO

mycsv = StringIO("""
time;openBid;highBid;lowBid;closeBid;openAsk;highAsk;lowAsk;closeAsk;volume
2015-12-06T22:00:00.000000Z;1.08703;1.08713;1.08703;1.08713;1.08793;1.08813;1.08793;1.08813;2
2015-12-07T22:00:05.000000Z;1.08682;1.08682;1.08662;1.08662;1.08782;1.08782;1.08762;1.08762;2
2015-12-08T22:01:20.000000Z;1.08683;1.08684;1.08681;1.08684;1.08759;1.08768;1.08759;1.08768;4
2015-12-09T22:01:30.000000Z;1.08676;1.08676;1.08676;1.08676;1.0876;1.0876;1.0876;1.0876;1
2015-12-10T00:03:00.000000Z;1.08675;1.08675;1.08675;1.08675;1.08737;1.08737;1.08737;1.08737;1
2015-12-06T22:03:10.000000Z;1.08675;1.08675;1.08675;1.08675;1.08728;1.08728;1.08728;1.08728;1
2015-12-06T22:03:50.000000Z;1.08676;1.08676;1.08676;1.08676;1.08728;1.08728;1.08728;1.08728;1
""")

df = pd.read_csv(mycsv, delimiter=';', parse_dates=True, index_col='time', header=0)
spr = df['lowAsk']-df['lowBid']
spr.plot()
plt.show()

我明白了:

enter image description here

问题:

如何在x轴上为每天添加刻度+标签+网格?

示例:Sun 06, Mon 07, Tue 08

我尝试了各种各样的事情,例如plt.axis(...),但它几乎没有成功。

1 个答案:

答案 0 :(得分:1)

您可以使用DayLocator中的DatesFormattermatplotlib.dates执行此操作。

来自文档:

  

DayLocator

     

勾选每月每天的出现次数

  

DateFormatter

     

使用strftime()格式字符串。

因此,在您的情况下,我们要将格式字符串设置为"%a %d"以获取Mon 07等。

当您拨打major_locator时,我们为major_formatter返回的xaxis的{​​{1}} Axespandas设置了这些

以下是你的例子:

spr.plot()

enter image description here