【问题标题】:How to enforce both xlim and ylim while using ax.axis('equal')?如何在使用 ax.axis('equal') 时同时执行 xlim 和 ylim?
【发布时间】:2016-09-29 16:38:08
【问题描述】:

我想使用ax.axis('equal') 在 X 和 Y 上强制均匀间距,但我也想为 X 和 Y 轴指定特定范围。如果边距也固定,则问题过度约束,结果显示在图1 的左侧。相反,如果允许边距自动增加以填补空白,那么xlimylim 可以保持我设置的状态,同时仍然满足axis('equal')。图1 的右侧显示了我所追求的示例。 如何让绘图边距“浮动”?

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

图 1:上述代码 sn-p 的输出。

【问题讨论】:

  • 你应该把set_xlimset_ylim放在最后,以避免自动重新缩放。
  • @dnalow 如果我删除ax.set_ylim() 之后的所有内容将不起作用,如果我在其他所有内容完成后将set_xlim()set_ylim() 复制到最后,则它不起作用。
  • 这是因为 `ax.axis('equal')。它修复了步进,因此 subplotsize 必须适合您的限制,这反过来意味着您的图形大小必须匹配或 subplot 参数
  • 除非边距自动调整大小,这是我所要求的。
  • 有趣且相关:autoscale() 中的 tight=True 关键字设置了 xlimylim,因此绘图框包含数据。 plt.autoscale(enable=True,axis='both',tight=True)

标签: python python-2.7 matplotlib plot


【解决方案1】:
ax.set_aspect('equal',adjustable='box')

【讨论】:

  • 我知道必须这么简单。
  • 顺便说一下,这个可以代替原问题中的ax.axis('equal')
  • adjustable='box-forced' 可能更可取,尤其是在共享轴时。见matplotlib.org/api/axes_api.html
猜你喜欢
  • 2017-02-05
  • 2020-11-25
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 2018-09-26
  • 2014-10-02
  • 1970-01-01
相关资源
最近更新 更多