2

I need to create histograms from the 2D arrays that I obtain from convolving an input array and a filter. The bins should as the range of the values in the array.

I tried following this example: How does numpy.histogram() work? The code is this:

import matplotlib.pyplot as plt
import numpy as np
plt.hist(result, bins = (np.min(result), np.max(result),1))
plt.show()

I always get this error message:

AttributeError: bins must increase monotonically.

Thanks for any help.

2
  • 1
    If you look at (np.min(result), np.max(result),1), do the values increase monotonically? Commented Jul 23, 2015 at 19:32
  • The min/max for my example is: '(0.0, 254.999999745)' Commented Jul 23, 2015 at 19:48

1 Answer 1

3

What you are actually doing is specifying three bins where the first bin is np.min(result), second bin is np.max(result) and third bin is 1. What you need to do is provide where you want the bins to be located in the histogram, and this must be in increasing order. My guess is that you want to choose bins from np.min(result) to np.max(result). The 1 seems a bit odd, but I'm going to ignore it. Also, you want to plot a 1D histogram of values, yet your input is 2D. If you'd like to plot the distribution of your data over all unique values in 1D, you'll need to unravel your 2D array when using np.histogram. Use np.ravel for that.

Now, I'd like to refer you to np.linspace. You can specify a minimum and maximum value and as many points as you want in between uniformly spaced. So:

bins = np.linspace(start, stop)

The default number of points in between start and stop is 50, but you can override this:

bins = np.linspace(start, stop, num=100)

This means that we generate 100 points in between start and stop.

As such, try doing this:

import matplotlib.pyplot as plt
import numpy as np
num_bins = 100 # <-- Change here - Specify total number of bins for histogram
plt.hist(result.ravel(), bins=np.linspace(np.min(result), np.max(result), num=num_bins)) #<-- Change here.  Note the use of ravel.
plt.show()
Sign up to request clarification or add additional context in comments.

9 Comments

I got this error message while implementing your example: 'UserWarning: 2D hist input should be nsamples x nvariables. this looks transposed (shape is 212 x 254)'.
I add that the min/max values are in float type.
@Litwos you didn't say that your input was 2D. You failed to mention that. Do you want to plot a 2D histogram or 1D?
It's a 2D array, I mentioned in the first post.
So do you want a 2D histogram or 1D?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.