Datetime axis spacing

空扰寡人 提交于 2019-12-06 11:17:20

An ugly fix for this could be the following

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()

The downside to this is that the axis objects are not of the datetime type so you can't use many functions.

You can use ax.margins to get what you want.

Without seeing your data, it's hard to know how big of a margin you actually want. If you're plotting with python datetime-types, a margin of 1 corresponds to a pretty big margin:

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)

But again, it's hard to get too specific without seeing your existing data and plots.

You can set spacing with margins()

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!