在DataFrame图上增加日期的x轴标签的频率

时间:2016-02-19 23:33:51

标签: pandas matplotlib plot axis-labels

我有一个包含两列的pandas DataFrame:month_of_sale是一个日期,number_of_gizmos_sold是一个数字。

我试图提高x轴上标签的频率,以便更容易阅读,但我不能!

这是我桌子的df.head()

DataFrame.head()

这就是它的情节: df.plot(y='number_of_gizmos_sold', figsize=(15,5))

DataFrame.plot()

我想增加标签的频率,因为它们之间有很大的空间。

我尝试了什么

plot.xaxis.set_major_locator(MonthLocator())但这似乎会增加标签之间的距离。

enter image description here

plot.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))

奇怪的是,我最终得到了这个: enter image description here

最后情节为我提出的问题是:

  • 今年什么是0002?
  • 为什么我还有旧的Jul标签呢?

1 个答案:

答案 0 :(得分:4)

我没有将问题追溯到其来源,但按bmu's solution,如果您致电ax.plot 而不是df.plot,那么您可以使用配置结果 ax.xaxis.set_major_locatorax.xaxis.set_major_formatter

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
np.random.seed(2016)

dates = pd.date_range('2013-03-01', '2016-02-01', freq='M')
nums = (np.random.random(len(dates))-0.5).cumsum()
df = pd.DataFrame({'months': dates, 'gizmos': nums})
df['months'] = pd.to_datetime(df['months'])
df = df.set_index('months')

fig, ax = plt.subplots()
ax.plot(df.index, df['gizmos'])
# df.plot(y='gizmos', ax=ax)
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
plt.show()

enter image description here

相关问题