Is there a way to return same length arrays in numpy.hist?

不羁岁月 提交于 2019-12-24 00:06:37

问题


I'm trying to create a histogram plot in python, normalizing with some custom values the y-axis values. For this, I was thinking to do it like this:

import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('foo.bar')
fig = plt.figure()
ax = fig.add_subplot(111)

hist=np.histogram(data, bins=(1.0, 1.5 ,2.0,2.5,3.0))
x=[hist[0]*5,hist[1]]
ax.plot(x[0], x[1], 'o')

but of course, the last line gives:

ValueError: x and y must have same first dimension

Is there a way to force np.hist to give the same number of elements for the x[0] and x[1] arrays, for example by deleting the first or last element for one of them?


回答1:


hist[1] contains the limits in which you have made the histogram. I guess you probably want to get the centers of those intervals, something like:

x = [hist[0], 0.5*(hist[1][1:]+hist[1][:-1])]

and then the plot should be ok, right?




回答2:


I would imagine it depends on your data source.

Try loading the data as a numpy array, and selecting the range of elements yourself before passing to the histogram function.

e.g.

dataForHistogram = data[0:100][0:100]   # Assuming your data is in this kind of structure.


来源:https://stackoverflow.com/questions/17966093/is-there-a-way-to-return-same-length-arrays-in-numpy-hist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!