Matplotlib:使折线图的日期时间 x 轴标签看起来像 Excel

Matplotlib: Making a line graph's datetime x axis labels look like Excel

我有一个简单的 pandas DataFrame,其中包含我绘制为折线图的年度值:

import matplotlib.pyplot as plt
import pandas as pd

>>>df
            a   b
2010-01-01  9.7 9.0
2011-01-01  8.8 14.2
2012-01-01  8.4 7.6
2013-01-01  9.6 8.4
2014-01-01  8.2 5.5

X 轴的预期格式是不对标签使用边距:

fig  = plt.figure(0)
ax = fig.add_subplot(1, 1, 1)
df.plot(ax = ax)

但我想强制将值绘制在年份范围的中间,就像在 excel:

中所做的那样

我试过设置 x 轴边距:

ax.margins(xmargin = 1)

但是看不出有什么区别。

如果你只是想移动日期,你可以尝试在最后添加这一行:

ax.set_xlim(ax.get_xlim()[0] - 0.5, ax.get_xlim()[1] + 0.5) 

如果您还需要格式化日期,您可以修改索引或更改绘制的刻度线,如下所示: (假设你df.index是一个datetime对象)

ax.set_xticklabels(df.index.to_series().apply(lambda x: x.strftime('%d/%m/%Y')))

这会将日期格式化为您的 Excel 示例。

或者您可以将 index 更改为您想要的样子,然后调用 .plot():

df.index = df.index.to_series().apply(lambda x: x.strftime('%d/%m/%Y'))
print df.index.tolist()

['01/01/2010', '01/01/2011', '01/01/2012', '01/01/2013', '01/01/2014']

而且,如果你的 index 不是 datetime 你需要先像这样转换它:

df.index = pd.to_datetime(df.index)