数据和直方图在matplotlib中不会发生冲突?

时间:2013-10-12 10:54:32

标签: python matplotlib

我正在为我的数据创建直方图。有趣的是,当我将原始数据和直方图一起绘制在一个图上时,它们是彼此的“y翻转”版本,如下所示:

enter image description here

我没有找到原因并修复它。我的代码段如下:

import math as mt
import numpy as np
import matplotlib.pylab as plt

x = np.random.randn(50)
y = np.random.randn(50)
w = np.random.randn(50)
leftBound, rightBound, topBound, bottomBound = min(x), max(x), max(y), min(y)
# parameters for histogram
x_edges = np.linspace(int(mt.floor(leftBound)), int(mt.ceil(rightBound)), int(mt.ceil(rightBound))-int(mt.floor(leftBound))+1)
y_edges = np.linspace(int(mt.floor(bottomBound)), int(mt.ceil(topBound)), int(mt.ceil(topBound))-int(mt.floor(bottomBound))+1)
# construct the histogram
wcounts = np.histogram2d(x, y, bins=(x_edges, y_edges), normed=False, weights=w)[0]
# wcounts is a 2D array, with each element representing the weighted count in a bins

# show histogram
extent = x_edges[0], x_edges[-1], y_edges[0], y_edges[-1]
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes.set_xlabel('x (m)')
axes.set_ylabel('y (m)')
histogram = axes.imshow(np.transpose(wcounts), extent=extent, alpha=1, vmin=0.5, vmax=5, cmap=cm.binary) # alpha controls the transparency
fig.colorbar(histogram)

# show data
axes.plot(x, y, color = '#99ffff')

由于这里的数据是为了演示而随机生成的,如果问题出在那个特定的数据集上,我觉得它不会有多大帮助。但无论如何,如果代码有问题,它仍然有帮助。

1 个答案:

答案 0 :(得分:3)

默认情况下,axes.imshow(z)将数组元素z[0,0]放在轴的左上角(或本例中的范围)。您可能希望在origin="bottom"调用中添加imshow()参数,或者传递翻转的数据数组,即z[:,::-1]