matplotlib '自动调整坐标轴'未显示所有数据点

2 投票
1 回答
4582 浏览
提问于 2025-04-16 17:38

我最近把matplotlib从版本'0.99.1.1'升级到了'1.0.1'。现在我遇到了一个新问题,跟“自动轴尺寸调整”有关……并不是所有的数据点都能显示出来。下面是一些代码,可以复现我的问题,后面还有更多讨论。

import datetime
from pylab import *
print matplotlib.__version__
x = [datetime.date(2011,2,11),
     datetime.date(2011,3,11),
     datetime.date(2011,4,11),
     datetime.date(2011,5,11),
     datetime.date(2011,6,11),
     datetime.date(2011,7,11)]
y = [23,41,67,72,18,19]
fig = figure()
ax = fig.add_subplot(111)
ax.plot_date(x, y, 'kx')

# next task is to broaden the xaxis so that it begins 
# and ends at the start of a month (approximately).  
xmin, xmax, ymin, ymax = ax.axis() ; print xmin, xmax, ymin, ymax
a1 = xmin - min(x).day + 1
a2 = xmax - max(x).day + 31

#a1 = datetime.date(1,1,1) + datetime.timedelta(a1)
#a2 = datetime.date(1,1,1) + datetime.timedelta(a2)

#ax.axis([a1,a2,ymin,ymax]) #

ax.plot_date(a1, ymin, 'ko')
ax.plot_date(a2, ymin, 'ko')

show()

在0.99.1版本下,上面的代码可以很好地解决(看起来)无法通过ax.axis(v)语句重置x轴的问题。而在1.0.1版本下,无论是用'a1'和'a2'以“天”还是“日期”的单位调用ax.plot_date,这两个'ko'点都显示在了轴的外面。

有可能这两个'ko'点根本没有被绘制出来。但如果想确认它们实际上是被绘制了,可以取消注释ax.axis(v)的调用(在1.0.1中这个是可以正常工作的),然后看看轴区域底角的两个四分之一圆。

虽然确实有更简洁的方法来扩展x轴,就是使用ax.axis(v)语句,但这种行为让我对“自动轴尺寸调整”感到不安……不过更可能的是我在代码上搞错了什么。

编辑:顺便说一下……以下代码可以精确地扩展到每个月的第一天。

xmin, xmax, ymin, ymax = ax.axis() #; print xmin, xmax, ymin, ymax
a1 = datetime.date.fromordinal(int(xmin)) #; print 'a1= ', a1
a2 = datetime.date.fromordinal(int(xmax)) #; print 'a2= ', a2

y1, m1 = a1.year, a1.month 
y2, m2 = a2.year, a2.month + 1

a1 = datetime.date(y1,m1,1) #; print 'a1= ', a1
a2 = datetime.date(y2,m2,1) #; print 'a2= ', a2

ax.axis([a1,a2,ymin,ymax])

1 个回答

2

发生的情况是,在你调用 ax.axis() 之后,坐标轴没有设置为“自动调整大小”。调用 axis 会关闭自动缩放功能(它假设如果你手动获取坐标轴的范围,你可能不希望它们发生变化)。

只需要在你绘制完所有内容后,添加 ax.axis('auto')ax.set_autoscale_on() 就可以了。

import datetime
import matplotlib.pyplot as plt
x = [datetime.date(2011,2,11),
     datetime.date(2011,3,11),
     datetime.date(2011,4,11),
     datetime.date(2011,5,11),
     datetime.date(2011,6,11),
     datetime.date(2011,7,11)]
y = [23,41,67,72,18,19]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot_date(x, y, 'kx')

# next task is to broaden the xaxis so that it begins 
# and ends at the start of a month (approximately).  
xmin, xmax, ymin, ymax = ax.axis() ; print xmin, xmax, ymin, ymax
a1 = xmin - min(x).day + 1
a2 = xmax - max(x).day + 31

ax.plot_date(a1, ymin, 'ko')
ax.plot_date(a2, ymin, 'ko')
ax.axis('auto')

plt.show()

撰写回答