日期时间轴间距

Datetime axis spacing

我有一个误差条图,其中 x 轴是日期时间对象的列表。标准绘图方法会将第一个点和最后一个点放在绘图的边界框上。我想抵消半个刻度,以便可以清楚地看到第一个和最后一个点。

ax.axis(xmin=-0.5,xmax=len(dates)-0.5)

由于显而易见的原因无法正常工作。如果能够在不对任何日期进行硬编码的情况下执行此操作,那就太好了。

以下将产生一个有 10 个点的图,但您实际上只能看到 8 个点。

import datetime
import matplotlib.pyplot as plt

dates = [datetime.date(2002, 3, 11) - datetime.timedelta(days=x) for x in range(0, 10)]
yvalues = [2, 4, 1,7,9,2, 4, 1,7,9]
errorvalues = [0.4, 0.1, 0.3,0.4, 0.1,.4, 0.1, 0.3,0.4, 0.1]

fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1)
ax.errorbar(dates,yvalues,yerr=errorvalues,fmt='.') 
fig.autofmt_xdate()

plt.show()

下面是一个丑陋的修复方法

fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1)
ax.errorbar(range(len(dates)),yvalues,yerr=errorvalues) 
ax.set_xticks(range(len(dates))
ax.set_xticklabels(dates, fontsize=8)
ax.axis(xmin=-0.5,xmax=len(dates)-0.5)
fig.autofmt_xdate()

这样做的缺点是轴对象不是日期时间类型,因此您不能使用很多函数。

您可以使用ax.margins来获得您想要的。

如果没有看到您的数据,就很难知道您真正想要的利润有多大。如果您使用 python 日期时间类型进行绘图,则边距 1 对应于相当大的边距:

fig, ax = plt.subplots()
ax.bar(x, y)
[t.set_ha('right') for t in ax.get_xticklabels()]
[t.set_rotation_mode('anchor') for t in ax.get_xticklabels()]
[t.set_rotation(45) for t in ax.get_xticklabels()]
ax.margins(x=1)

但同样,如果不查看您现有的数据和图表,就很难说得太具体。

你可以设置边距()

import datetime
import matplotlib.pyplot as plt

dates = [datetime.date(2002, 3, 11) - datetime.timedelta(days=x) for x in range(0, 10)]
yvalues = [2, 4, 1,7,9,2, 4, 1,7,9]
errorvalues = [0.4, 0.1, 0.3,0.4, 0.1,.4, 0.1, 0.3,0.4, 0.1]

fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1)
ax.errorbar(dates,yvalues,yerr=errorvalues,fmt='.') 
ax.margins(x=0.05)
fig.autofmt_xdate()

plt.show()