数据和直方图在 matplotlib 中不冲突? [英] Data and histogram do not collide in matplotlib?

查看:27
本文介绍了数据和直方图在 matplotlib 中不冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a histogram for my data. Interestingly, when I plot my raw data and their histogram together on one plot, they are a "y-flipped" version of each other as follows:

我未能找出原因并修复它.我的代码片段如下:

I failed to find out the reason and fix it. My code snippet is as follows:

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

由于这里的数据是随机生成的用于演示,因此,如果问题出在该特定数据集上,我认为它没有太大帮助.但无论如何,如果代码有问题,它仍然有帮助.

Since the data here are generated randomly for demonstration, I don't think it helps much, if the problem is with that particular data set. But anyway, if it is something wrong with the code, it still helps.

推荐答案

默认情况下, axes.imshow(z)将数组元素 z [0,0] 放入轴的左上角(或在这种情况下为范围).您可能想将 origin ="bottom" 参数添加到您的 imshow()调用中,或传递一个翻转的数据数组,即 z [:,::-1].

By default, axes.imshow(z) places array element z[0,0] in the top left corner of the axes (or the extent in this case). You probably want to either add the origin="bottom" argument to your imshow() call or pass a flipped data array, i.e., z[:,::-1].

这篇关于数据和直方图在 matplotlib 中不冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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