【问题标题】:Force pandas xaxis datetime index using a specific format使用特定格式强制 pandas xaxis 日期时间索引
【发布时间】:2016-07-01 22:15:38
【问题描述】:

我的 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
....

在我绘制之后

 plt.style.use('ggplot')
 df.plot(subplots=True, style=style, title='some title', grid=True, x_compat=True)

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

【问题讨论】:

  • 获取对底部 Axes 对象的引用,然后是 ax.xaxis.set_major_formatterax.axis.set_major_locator 使用您想要从 matplotlib.org/api/dates_api.html#date-tickers 获得的任何定位器和格式化程序
  • tcaswell,您能否再解释一下我是如何获得对坐标轴的引用的?

标签: python pandas matplotlib


【解决方案1】:

你必须使用 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()    

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-17
    • 2020-10-04
    • 2015-12-03
    • 2017-04-24
    • 2019-05-08
    • 2017-07-11
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多