Datetime axis spacing

一个人想着一个人 提交于 2019-12-22 11:59:40

问题


I have an errorbar plot where the xaxis is a list of datetime objects. The standard plotting method will put the first and last point so that they are right on the bounding box of the plot. I would like to offset by a half tick so that the first and last point can be seen clearly.

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

does not work for obvious reasons. It would be nice to be able to do this without hardcoding any dates.

The following will produce a plot which has ten points but you can really only see 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()

回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/30445708/datetime-axis-spacing

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