Matplotlib垂直拉伸直方图 [英] Matplotlib stretches histogram2d vertically

查看:78
本文介绍了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()

这篇关于Matplotlib垂直拉伸直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆