Matplotlib垂直拉伸histogram2d

时间:2013-06-04 12:27:20

标签: python matplotlib histogram2d

我正在使用此代码:

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直方图,然而,绘图是垂直拉伸的,我根本无法弄清楚如何正确设置其大小:

Matplotlib stretches 2d histogram vertically

2 个答案:

答案 0 :(得分:4)

由于您正在使用imshow,因此事情已“拉长”。默认情况下,它假定您要显示图表的纵横比为1(在数据坐标中)的图像。

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

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

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

enter image description here

我们只需将aspect="auto"添加到imshow来电即可解决问题:

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

enter image description here

答案 1 :(得分:2)

不确定,但我认为你应该尝试修改你的historygram2d:

H, xedges, yedges = np.histogram2d(x, y, bins=(25, 25), range=[[-50, 50], [0, 10]])

编辑: 我没有找到如何确切地修复比例,但是使用aspect ='auto',matplotlib猜对了:

plt.imshow(hist.T, extent=extent, interpolation='nearest', aspect='auto')