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

Increasing Frequency of x-axis labels for dates on DataFrame plot

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

我想增加 x 轴上标签的频率,以便更容易阅读,但我做不到!

这是我的 table 的 df.head():

这就是它绘制的内容: df.plot(y='number_of_gizmos_sold', figsize=(15,5))

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

我试过的

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

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

奇怪的是,我最终得到了这个:

最后一个情节给我提出的问题是:

我还没有追查问题的根源,但根据 bmu 的 解决方案,如果你调用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()