使用特定格式强制pandas xaxis datetime索引

use*_*662 4 python matplotlib pandas

我的pandas数据框看起来像这样:

                      data1   data2         data3
DateTime
....                                       
2016-04-18 16:16:53     -66       1       94.8654
2016-04-18 16:17:03     -67       1       94.8601
2016-04-18 16:17:13     -68       1       94.8410
2016-04-18 16:17:23     -69       1       94.8753
2016-04-18 16:17:33     -70       1       94.8535
2016-04-18 16:17:43     -71       1       94.8529
2016-04-18 16:17:53     -72       1       94.8702
....
Run Code Online (Sandbox Code Playgroud)

我用它绘制后

 plt.style.use('ggplot')
 df.plot(subplots=True, style=style, title='some title', grid=True, x_compat=True)
Run Code Online (Sandbox Code Playgroud)

情节只显示小时数.
1)如何让它显示日期?
2)如何强制它显示我想要的任何格式?

情节

Ser*_*ity 6

您必须使用matplotlib.dates模块中的函数:

import pandas as pd
from datetime import datetime
import numpy as np
import matplotlib.pylab as plt
import matplotlib.dates as mdates

timeInd = pd.date_range(start = datetime(2016,4,17,23,0,0), 
 end = datetime(2016,4,20,1,0,0), freq = 'H')
d = {'data1': np.random.randn(len(timeInd)), 'data2': np.random.randn(len(timeInd)),
 'data3': np.random.randn(len(timeInd))}
df = pd.DataFrame(data = d, index = timeInd)  

plt.style.use('ggplot')
df.plot(subplots=True, grid=True, x_compat=True)
ax = plt.gca()
# set major ticks location every day
ax.xaxis.set_major_locator(mdates.DayLocator())
# set major ticks format
ax.xaxis.set_major_formatter(mdates.DateFormatter('\n\n\n%d.%m.%Y'))
# set minor ticks location every two hours
ax.xaxis.set_minor_locator(mdates.HourLocator(interval=2))
# set minor ticks format
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M:%S'))

# or just set together date and time for major ticks like
# ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%Y %H:%M:%S'))

plt.show()    
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

更多示例:http://matplotlib.org/examples/api/date_demo.html