2016-09-27 383 views
3

我使用ax.axes('equal')做出关于X和Y轴间距相等,并且还设置xlimylim。这会限制这个问题,实际限制并不是我在ax.set_xlim()ax.set_ylim()中设置的。使用ax.get_xlim()只是返回我提供的。我怎样才能得到情节的实际可见限度?如何在使用ax.axis('equal')时获得实际的轴限制?

f,ax=plt.subplots(1) #open a figure 
ax.axis('equal') #make the axes have equal spacing 
ax.plot([0,20],[0,20]) #test data set 

#change the plot axis limits 
ax.set_xlim([2,18]) 
ax.set_ylim([5,15]) 

#read the plot axis limits 
xlim2=array(ax.get_xlim()) 
ylim2=array(ax.get_ylim()) 

#define indices for drawing a rectangle with xlim2, ylim2 
sqx=array([0,1,1,0,0]) 
sqy=array([0,0,1,1,0]) 

#plot a thick rectangle marking the xlim2, ylim2 
ax.plot(xlim2[sqx],ylim2[sqy],lw=3) #this does not go all the way around the edge 

什么命令会让我在图形的实际边缘周围绘制绿色框?

Plot showing that the results of get_xlim() and get_ylim() do not match the visible bounds of the figure

相关:Force xlim, ylim, and axes('equal') at the same time by letting margins auto-adjust

+0

我能得到的改''通过ax.callbacks.connect ylim'通知(“ylim_changed”,ylim_ch)',但它仍然会返回给'set_ylim'的价值,而不是显示什么。请参阅http://stackoverflow.com/questions/31490436/matplotlib-finding-out-xlim-and-ylim-after-zoom –

回答

2

,直到图绘制的实际限制是不知道的。通过在设置xlimylim之后但在获得xlimylim之后添加画布绘制,则可以获得期望的限制。

f,ax=plt.subplots(1) #open a figure 
ax.axis('equal') #make the axes have equal spacing 
ax.plot([0,20],[0,20]) #test data set 

#change the plot axis limits 
ax.set_xlim([2,18]) 
ax.set_ylim([5,15]) 

#Drawing is crucial 
f.canvas.draw() #<---------- I added this line 

#read the plot axis limits 
xlim2=array(ax.get_xlim()) 
ylim2=array(ax.get_ylim()) 

#define indices for drawing a rectangle with xlim2, ylim2 
sqx=array([0,1,1,0,0]) 
sqy=array([0,0,1,1,0]) 

#plot a thick rectangle marking the xlim2, ylim2 
ax.plot(xlim2[sqx],ylim2[sqy],lw=3) 

Figure produced by script

+0

这是否意味着脚本终止时会自动执行f.canvas.draw()? –

+1

这意味着有一个GUI循环等待空闲时间来调用'draw'方法,在脚本完成后出现空闲... – esmit

1

不从公认的答案,这也解决了得到更新轴限制问题减损,但是这也许是XY问题的例子吗?如果你想要做的就是绘制轴周围的框,那么你实际上并不需要xlimylim数据坐标。相反,你只需要使用ax.transAxes变换导致双方xy数据归一化坐标,而不是数据中心的坐标来解释:

ax.plot([0,0,1,1,0],[0,1,1,0,0], lw=3, transform=ax.transAxes) 

关于这个伟大的事情是,你的行会留周围的轴的边缘即使xlimylim随后更改

您还可以使用transform=ax.xaxis.get_transform()transform=ax.yaxis.get_transform()如果你只想x或仅y在归一化坐标来定义,数据坐标中的另一个。

+0

我的问题比只画一个盒子更普遍,所以我喜欢接受回答(这些评论也澄清了我对剧情展示的误解),但这是很了解的。谢谢。 –

相关问题