【问题标题】:How can I get the actual axis limits when using ax.axis('equal')?使用 ax.axis('equal') 时如何获得实际的轴限制?
【发布时间】:2017-02-05 10:16:30
【问题描述】:

我使用ax.axes('equal') 使X 和Y 上的轴间距相等,并设置xlimylim。这过度约束了问题,实际限制不是我在ax.set_xlim()ax.set_ylim() 中设置的。使用 ax.get_xlim() 只会返回我提供的内容。如何获得绘图的实际可见限制?

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

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

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

【问题讨论】:

标签: python python-2.7 matplotlib plot


【解决方案1】:

不要减损已接受的答案,这确实解决了获取更新轴限制的问题,但这可能是 XY 问题的一个例子吗?如果您想要做的是围绕轴绘制一个框,那么您实际上并不需要数据坐标中的xlimylim。相反,您只需要使用ax.transAxes 转换,它会导致xy 数据以归一化坐标而不是以数据为中心的坐标进行解释:

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

这样做的好处是,即使 xlimylim 随后发生变化,您的线也会保持在轴的边缘

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

【讨论】:

  • 我的问题不仅仅是画一个盒子,所以我喜欢接受的答案(cmets 也澄清了我对情节如何显示的误解),但很高兴知道.谢谢。
  • 这是一个了不起的技巧!我一直在使用 xlim 和 ylim 来自定义图形上的标签(例如“(a)”和“(b)”)。在设置axis('equal') 之后,我遇到了这个答案,试图弄清楚如何去做。这比我多年来一直使用的方法要优雅得多。
【解决方案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) 

【讨论】:

  • 这是否意味着脚本终止时有一个自动的 f.canvas.draw() ?
  • 表示有一个GUI循环等待空闲时间调用draw方法,这里的空闲时间是在脚本执行完之后出现的......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-30
相关资源
最近更新 更多