Plotting random points under sine curve in Python Matplotlib

In this tutorial, we are going to learn about Plotting random points under the sine curve in Python using Matplotlib library.

We will be learning today how to generate numbers randomly and then we will be plotting those numbers on a sine curve.

Let us first see what these libraries are…

 

NumPy:

We have imported the NumPy library because, for the Python programming language, it adds support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.

 

Matplotlib:

We have imported the Matplotlib library because it is a plotting library for the Python programming language and its numerical mathematics extension NumPy.

 

So, to use any of these libraries first we need to import them…

 

Importing the required libraries:

 

Firstly, we will import the Numpy library as “np” and Matplotlib library as “plt”.

 

import numpy as np
import matplotlib.pyplot as plt

 

Generating random numbers:

We will be using the random function available in the Numpy library because it generates random points for plotting. Here, we have added the uniform function with the random function. The uniform() method returns a random floating number between the two specified numbers (both included).

 

Here, we are generating 30 points using the function in (-4,4).

x = np.random.uniform(-4, 4, size=30)

 

Using the sine curve:

Now, we will be generating the sine curve with the points generated above.

y = np.sin(x)

Here, np.sin() function is the sine function in the python language.

 

Plotting the curve:

Now, we plot the curve.

fig, ax = plt.subplots()
ax.scatter(x,y)
plt.show()

Here we have defined that we are going to plot a scatter plot of the randomly generated points.

Now, let us look at what we have got…

 

Output:

plot

The output above clearly shows us that the random points generated plotted on a sine curve.

 

And that how we successfully plot random points under sine curve in Python using Matplotlib.

I hope you enjoyed the tutorial.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *