Python 以AM/PM格式打印Datetime时间序列

Python 以AM/PM格式打印Datetime时间序列,python,pandas,datetime,plot,date-arithmetic,Python,Pandas,Datetime,Plot,Date Arithmetic,我有一个带有时间戳索引的熊猫系列,我想画出来 print example.head() 2015-08-11 20:07:00-05:00 26 2015-08-11 20:08:00-05:00 66 2015-08-11 20:09:00-05:00 71 2015-08-11 20:10:00-05:00 63 2015-08-11 20:11:00-05:00 73 但当我在《大熊猫》中用以下文字描绘它时: plt.figure(figsize = (1

我有一个带有时间戳索引的熊猫系列,我想画出来

print example.head()

2015-08-11 20:07:00-05:00    26
2015-08-11 20:08:00-05:00    66
2015-08-11 20:09:00-05:00    71
2015-08-11 20:10:00-05:00    63
2015-08-11 20:11:00-05:00    73
但当我在《大熊猫》中用以下文字描绘它时:

plt.figure(figsize = (15,8))
cubs1m.plot(kind='area')
我希望y轴上的值以AM/PM格式(8:08PM)显示,而不是军事时间(20:08)。有没有一个简单的方法可以做到这一点

还有,我如何控制蜱虫的数量和熊猫标绘标签的数量


提前感谢。

您的问题有两个要素:

  • 如何控制绘图上记号/标签的数量
  • 如何将24小时制改为12小时制
  • 轴方法
    set_-xticks
    set_-yticks
    set_-xticklabels
    ,以及
    set_-yticklabels
    控制标记和标签:

    import matplotlib.pyplot as plt
    
    plt.plot(range(10), range(10))
    plt.gca().set_xticks(range(0,10,2))
    plt.gca().set_xticklabels(['a{}'.format(ii) for ii in range(0,10,2)])
    
    要更改时间格式,请使用pd.datetime.strftime:

    本问题涵盖了另一种绘制日期的方法:

    import pandas as pd
    
    data = pd.Series(range(12), index=pd.date_range('2016-2-3 9:00','2016-2-3 20:00', freq='H'))
    ax = data.plot(xticks=data.index[::2])
    ax.set_xticklabels(data.index[::2].map(lambda x: pd.datetime.strftime(x, '%I %p')))