展示:范围和方面 [英] Imshow: extent and aspect
问题描述
我正在编写一个软件系统,该软件可以通过3D数据集可视化切片和投影.我正在使用matplotlib
,特别是imshow
来可视化从分析代码中获得的图像缓冲区.
I'm writing a software system that visualizes slices and projections through a 3D dataset. I'm using matplotlib
and specifically imshow
to visualize the image buffers I get back from my analysis code.
由于我想用绘图轴注释图像,因此我使用imshow
提供的程度上关键字将图像缓冲区像素坐标映射到数据空间坐标系.
Since I'd like to annotate the images with plot axes, I use the extent keyword that imshow
supplies to map the image buffer pixel coordinates to a data space coordinate system.
不幸的是,matplotlib
不知道单位.说(以人工示例为例),我想绘制尺寸为1000 m X 1 km
的图像.在这种情况下,范围将类似于[0, 1000, 0, 1]
.即使图像阵列是正方形的,由于由range关键字暗示的长宽比是1000,因此生成的绘图轴的长宽比也为1000.
Unfortuantely, matplotlib
doesn't know about units. Say (taking an artificial example) that I want to plot an image with dimensions of 1000 m X 1 km
. In that case the extent would be something like [0, 1000, 0, 1]
. Even though the image array is square, since the aspect ratio implied by the extent keyword is 1000, the resulting plot axes also have an aspect ratio of 1000.
是否可以强制使用绘图的宽高比,同时仍然保留通过使用range关键字获得的自动生成的主要刻度线和标签?
Is it possible to force the aspect ratio of the plot while still keeping the automatically generated major tick marks and labels I get by using the extent keyword?
推荐答案
您可以通过手动设置图像的外观(或通过使其自动缩放以填满图形的范围)来做到这一点.
You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure).
默认情况下,imshow
将图的宽高比设置为1,因为这通常是人们想要的图像数据.
By default, imshow
sets the aspect of the plot to 1, as this is often what people want for image data.
对于您而言,您可以执行以下操作:
In your case, you can do something like:
import matplotlib.pyplot as plt
import numpy as np
grid = np.random.random((10,10))
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))
ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')
ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')
ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')
plt.tight_layout()
plt.show()
这篇关于展示:范围和方面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!