gpt4 book ai didi

python - Matplotlib 垂直拉伸(stretch) histogram2d

转载 作者:行者123 更新时间:2023-11-28 21:23:46 30 4
gpt4 key购买 nike

我正在使用这段代码:

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

然而,为了生成二维直方图,该图被垂直拉伸(stretch),我根本不知道如何正确设置它的大小:

Matplotlib stretches 2d histogram vertically

最佳答案

因为您正在使用 imshow,所以事情被“拉伸(stretch)”了。默认情况下,它假定您要显示图像,其中绘图的纵横比为 1(在数据坐标中)。

如果您想禁用此行为,并让像素拉伸(stretch)以填满绘图,只需指定 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

关于python - Matplotlib 垂直拉伸(stretch) histogram2d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16917836/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com