Matplotlib垂直拉伸直方图

问题描述:

我正在使用此代码:

fig = plt.figure(num=2, figsize=(8, 8), dpi=80,
                 facecolor='w', edgecolor='k')
x, y = [xy for xy in zip(*self.pulse_time_distance)]
H, xedges, yedges = np.histogram2d(x, y, bins=(25, 25))
extent = [-50, +50, 0, 10]
plt.imshow(H, extent=extent, interpolation='nearest')
plt.colorbar()

要生成2D直方图,但是该图是垂直拉伸的,我根本无法弄清楚如何正确设置其大小:

to produce a 2D histogram, however, the plot is stretched vertically and I simply can't figure out how to set its size properly:

由于您正在使用 imshow ,因此事情被拉伸了".默认情况下,假定您要显示图像的纵横比为1(在数据坐标中).

Things are "stretched" because you're using imshow. By default, it assumes that you want to display an image where the aspect ratio of the plot will be 1 (in data coordinates).

如果要禁用此行为,并且使像素拉伸以填充图,只需指定 aspect ="auto" .

If you want to disable this behavior, and have the pixels stretch to fill up the plot, just specify aspect="auto".

例如,要重现您的问题(基于您的代码段):

For example, to reproduce your problem (based on your code snippet):

import matplotlib.pyplot as plt
import numpy as np

# Generate some data
x, y = np.random.random((2, 500))
x *= 10

# Make a 2D histogram
H, xedges, yedges = np.histogram2d(x, y, bins=(25, 25))

# Plot the results
fig, ax = plt.subplots(figsize=(8, 8), dpi=80, facecolor='w', edgecolor='k')

extent = [-50, +50, 0, 10]
im = ax.imshow(H, extent=extent, interpolation='nearest')
fig.colorbar(im)

plt.show()

我们可以通过在 imshow 调用中添加 aspect ="auto" 来解决此问题:

And we can fix it by just adding aspect="auto" to the imshow call:

import matplotlib.pyplot as plt
import numpy as np

# Generate some data
x, y = np.random.random((2, 500))
x *= 10

# Make a 2D histogram
H, xedges, yedges = np.histogram2d(x, y, bins=(25, 25))

# Plot the results
fig, ax = plt.subplots(figsize=(8, 8), dpi=80, facecolor='w', edgecolor='k')

extent = [-50, +50, 0, 10]
im = ax.imshow(H, extent=extent, interpolation='nearest', aspect='auto')
fig.colorbar(im)

plt.show()