w3resource

NumPy: Compute the line graph of a set of data

NumPy: Array Object Exercise-117 with Solution

Write a NumPy program to compute the line graph of a set of data.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Importing the matplotlib.pyplot module and aliasing it as 'plt'
import matplotlib.pyplot as plt

# Generating a NumPy array 'arr' with 10 random integers between 1 and 50 (excluding 50)
arr = np.random.randint(1, 50, 10)

# Creating a histogram with np.histogram()
# 'y' stores the frequencies, 'x' stores the bin edges using np.arange(51) (from 0 to 50)
y, x = np.histogram(arr, bins=np.arange(51))

# Creating a figure and axis using plt.subplots()
fig, ax = plt.subplots()

# Plotting the histogram by plotting the bin edges against frequencies
ax.plot(x[:-1], y)

# Displaying the figure
fig.show()

Sample Output:

Line graph image

Explanation:

In the above code –

arr = np.random.randint(1, 50, 10): This line generates an array of 10 random integers between 1 and 49 (inclusive) using np.random.randint() function.

y, x = np.histogram(arr, bins=np.arange(51)): This line computes the histogram of the random integers using np.histogram() function with bins from 0 to 50 (51 bins in total). y will contain the frequency counts for each bin, and x will contain the bin edges.

fig, ax = plt.subplots(): Create a Matplotlib figure and axis object using the plt.subplots() function. This will be used to create and customize the line plot.

ax.plot(x[:-1], y): Plot the histogram on the axis object ax using the ax.plot() function. Since x contains the bin edges, we use x[:-1] to exclude the last bin edge and match the length of y.

Finally fig.show() function displays the line plot of the histogram with the bins on the x-axis and their corresponding counts on the y-axis.

Python-Numpy Code Editor:

Previous: Write a NumPy program to compute the histogram of a set of data.
Next: Write a NumPy program to find the position of the index of a specified value greater than existing value in numpy array.

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://198.211.115.131/python-exercises/numpy/python-numpy-exercise-117.php