简体   繁体   English

日期时间轴间距

[英]Datetime axis spacing

I have an errorbar plot where the xaxis is a list of datetime objects. 我有一个误差线图,其中xaxis是日期时间对象的列表。 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. 下面将产生一个包含十个点的图,但实际上您只能看到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()

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. 您可以使用ax.margins获取所需的内容。

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: 如果要使用python datetime-types进行绘图,则裕度为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)

But again, it's hard to get too specific without seeing your existing data and plots. 但是同样,如果不查看现有数据和图表,很难变得过于具体。

You can set spacing with margins() 您可以使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM