w3resource

NumPy: Compute the histogram of nums against the bins

NumPy Statistics: Exercise-14 with Solution

Write a NumPy program to compute the histogram of nums against the bins.

Sample Solution:

Python Code:

# Importing necessary libraries
import numpy as np
import matplotlib.pyplot as plt

# Creating an array of numbers
nums = np.array([0.5, 0.7, 1.0, 1.2, 1.3, 2.1])

# Defining the bins
bins = np.array([0, 1, 2, 3])

# Displaying the original arrays
print("nums: ", nums)
print("bins: ", bins)

# Calculating the histogram using numpy's histogram function
print("Result:", np.histogram(nums, bins))

# Creating a histogram plot using matplotlib
plt.hist(nums, bins=bins)

# Displaying the histogram
plt.show() 

Sample Output:

nums:  [0.5 0.7 1.  1.2 1.3 2.1]
bins:  [0 1 2 3]
Result: (array([2, 3, 1], dtype=int64), array([0, 1, 2, 3]))
NumPy Statistics: Compute the histogram of nums against the bins

Explanation:

In the above exercise –

nums = np.array([0.5, 0.7, 1.0, 1.2, 1.3, 2.1]): This code creates a NumPy array containing the numbers to be plotted on the histogram.

bins = np.array([0, 1, 2, 3]): This code creates a NumPy array containing the bin edges for the histogram.

print("Result:", np.histogram(nums, bins)): This line calculates and prints the histogram of the given numbers using the specified bins. np.histogram returns two arrays: the histogram values and the bin edges.

plt.hist(nums, bins=bins): This line plots the histogram using Matplotlib's hist() function. The bins parameter specifies the bin edges to use.

plt.show(): This line displays the histogram plot.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to count number of occurrences of each value in a given array of non-negative integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-stat-exercise-14.php