Lizi Swann
Lizi Swann

Reputation: 93

matplotlib.pyplot.hist returns a histogram where all bins have the same value when I have varying data

I am trying to create a histogram in python using matplotlib.pyplot.hist. I have an array of data that varies, however when put my code into python the histogram is returned with values in all bins equal to each other, or equal to zero which is not correct.

The histogram should look the the line graph above it with bins roughly the same height and in the same shape as the graph above.

The line graph above the histogram is there to illustrate what my data looks like and to show that my data does vary.

My data array is called spectrumnoise and is just a function I have created against an array x

x=np.arange[0.1,20.1,0.1]

The code I am using to create the histogram and the line graph above it is

import matplotlib.pylot as mpl 
mpl.plot(x,spectrumnoise)
mpl.hist(spectrumnoise,bins=50,histtype='step')
mpl.show()

I have also tried using

mpl.hist((x,spectrumnoise),bins=50,histtype=step)

I have also changed the number of bins countless times to see if that helps an normalising the histogram function but nothing works.

Image of the output of the code can be seen here enter image description here

Upvotes: 1

Views: 4050

Answers (1)

ali_m
ali_m

Reputation: 74252

The problem is that spectrumnoise is a list of arrays, not a numpy.ndarray. When you hand hist a list of arrays as its first argument, it treats each element as a separate dataset to plot. All the bins have the same height because each 'dataset' in the list has only one value in it!

From the hist docstring:

Multiple data can be provided via x as a list of datasets of potentially different length ([x0, x1, ...]), or as a 2-D ndarray in which each column is a dataset.

Try converting spectrumnoise to a 1D array:

pp.hist(np.vstack(spectrumnoise),50)

As an aside, looking at your code there's absolutely no reason to convert your data to lists in the first place. What you ought to do is operate directly on slices in your array, e.g.:

data[20:40] += y1

Upvotes: 1

Related Questions