以显示的纵横比来指定,而不是数据范围。

huangapple go评论63阅读模式
英文:

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))"

英文:

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))

以显示的纵横比来指定,而不是数据范围。

huangapple
  • 本文由 发表于 2023年7月4日 20:44:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76612782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定