英文:
Specify aspect ratio in terms of displayed aspect ratio, not data ranges
问题
如何在matplotlib.pyplot.imshow
中以实际显示的纵横比来指定纵横比?在imshow
中,选项aspect
以列数和行数的比例来指定纵横比。考虑以下代码:
z = np.random.rand(10,1000)
plt.imshow(z, aspect=1)
直观地说,我希望这会创建一个正方形图像(x和y的大小相等)。然而,实际上它创建了一个非常细长的图像,显示的纵横比为100。有没有一种优雅的方法来实现我想要的效果?我知道我可以提取列数和行数,然后使用它们来定义纵横比,但这似乎是一种很不正式的方法。此外,当我修改例如xlim
时,我需要显示的纵横比保持不变。
英文:
How can I specify the aspect ratio in matplotlib.pyplot.imshow
in terms of the actual displayed aspect ratio. In imshow
the option aspect
specifies the ratio in terms of the number of columns and rows. Consider the following code
z = np.random.rand(10,1000)
plt.imshow(z, aspect=1)
Intuitively I would expect this to create a square image (equal size of x and y). However it actually creates a super elongated image with a display aspect ratio of 100. Is there an elegant way to accomplish want I want. I know that I can extract the number of columns and rows and use those to define the aspect ratio, but this seems super hacky. Moreover, I need the displayed aspect ratio to stay the same when I modify, for example, the xlim
答案1
得分: 2
你可以将 aspect 设置为 ´auto´
以始终填充绘图区域与数据。对于图像,您可能还希望关闭插值:
plt.imshow(z, aspect='auto', interpolation='None')
英文:
You can set the aspect to ´auto´
to always fill the plot area with data. In case of an image, you may want to additionally switch off interpolation:
plt.imshow(z, aspect='auto', interpolation='None')
答案2
得分: 2
如果您需要绘图的边界框是正方形的,无论坐标轴上的数据大小如何,请尝试以下方法:
import numpy as np
import matplotlib.pyplot as plt
z = np.random.rand(10, 1000)
plt.imshow(z, aspect='auto').axes.set_box_aspect(1)
plt.show()
英文:
If you need the bounding box of the plot to be square, regardless of the size of the data on the axes, try this:
import numpy as np
import matplotlib.pyplot as plt
z = np.random.rand(10, 1000)
plt.imshow(z, aspect='auto').axes.set_box_aspect(1)
plt.show()
答案3
得分: 1
我将翻译您提供的内容:
"For a squared figure, I would take the ratio between the number of elements in each sub-array and the number of sub-arrays.
plt.imshow(z, aspect=len(z[0])/len(z))"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论