- Plotting mathematical expression using matplotlib in Python
- What is Matplotlib.pyplot?
- Plot Y = X² using matplotlib in Python
- Plot parabola using matplotlib in Python
- y= cos(x) plotting using matplotlib in Python
- Plot Mathematical Expressions in Python using Matplotlib
- Matplotlib.pyplot
- Plotting the equation
- Python3
- Customization of plots
- Plotting Equations with Python in Matplotlib
- Plotting y = x 2
- Plotting y = Sin(x) + x
- Some cool graphs
Plotting mathematical expression using matplotlib in Python
In this article, we are going to learn to plot basic equations in Python. This article also contains a few different examples for better understanding, and then I will provide the code to develop plots.
- Learn to Create an array of the vector.
- Manipulating vector to match equations.
- Creating plots with axis labels, title, and grid/place.
We will use two basic modules:
1.Matplotlib.pyplot(for plotting graphs)
2.Numpy(for creating sample array)
What is Matplotlib.pyplot?
Matplotlib is one of the most popular libraries in Python when it comes to data visualization.
Plot Y = X² using matplotlib in Python
But first, let’s start our work with one of the basic equation Y = X². Let plot 100 points on the X-axis. In this scenario, every value of Y is a square of the X value at the same index.
# Importing the libraries import matplotlib.pyplot as plt import numpy as np # Creating vectors X and Y x = np.linspace(-2, 2, 100) y = x**2 fig = plt.figure(figsize = (10, 5)) # Create the plot plt.plot(x, y) # Show the plot plt.show()
NOTE: The number of points that we use is being used entirely arbitrarily, but the goal here is to show a smooth graph for a smooth curve and so we have to choose a sufficient number based on the function. But be careful to generate too many points because a large number of points will require a long time to plot.
Plot parabola using matplotlib in Python
A plot is created using some modifications below:
# Import libraries import matplotlib.pyplot as plt import numpy as np # Createing vectors X and Y x = np.linspace(-2, 2, 100) y = x ** 2 fig = plt.figure(figsize = (12, 7)) # Create the plot plt.plot(x, y, alpha = 0.4, label ='Y = X²', color ='red', linestyle ='dashed', linewidth = 2, marker ='D', markersize = 5, markerfacecolor ='blue', markeredgecolor ='blue') # Add a title plt.title('Equation plot') # Add X and y Label plt.xlabel('x axis') plt.ylabel('y axis') # Add Text watermark fig.text(0.9, 0.15, 'Code Speedy', fontsize = 12, color ='green', ha ='right', va ='bottom', alpha = 0.7) # Add a grid plt.grid(alpha =.6, linestyle ='--') # Add a Legend plt.legend() # Show the plot plt.show()
y= cos(x) plotting using matplotlib in Python
Plotting a graph of the function y = Cos (x) with its polynomial 2 and 4 degrees.
# Import libraries import matplotlib.pyplot as plt import numpy as np x = np.linspace(-6, 6, 50) fig = plt.figure(figsize = (14, 8)) # Plot y = cos(x) y = np.cos(x) plt.plot(x, y, 'b', label ='cos(x)') # Plot degree 2 Taylor polynomial y2 = 1 - x**2 / 2 plt.plot(x, y2, 'r-.', label ='Degree 2') # Plot degree 4 Taylor polynomial y4 = 1 - x**2 / 2 + x**4 / 24 plt.plot(x, y4, 'g:', label ='Degree 4') # Add features to our figure plt.legend() plt.grid(True, linestyle =':') plt.xlim([-6, 6]) plt.ylim([-4, 4]) plt.title('Taylor Polynomials of cos(x) at x = 0') plt.xlabel('x-axis') plt.ylabel('y-axis') # Show plot plt.show()
Let’s take another example-
What about creating an array of 10000 random entries, sampling involving the normal distribution, and creating a histogram with a normal distribution of the equation:
y=1 ∕ √2πe -x^2/2
# Import libraries import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize = (14, 8)) # Creating histogram samples = np.random.randn(10000) plt.hist(samples, bins = 30, density = True, alpha = 0.5, color =(0.9, 0.1, 0.1)) # Add a title plt.title('Random Samples - Normal Distribution') # Add X and y Label plt.ylabel('X-axis') plt.ylabel('Frequency') # Creating vectors X and Y x = np.linspace(-4, 4, 100) y = 1/(2 * np.pi)**0.5 * np.exp(-x**2 / 2) # Creating plot plt.plot(x, y, 'b', alpha = 0.8) # Show plot plt.show()
Plot Mathematical Expressions in Python using Matplotlib
Numpy is a core library used in Python for scientific computing. This Python library supports you for a large, multidimensional array object, various derived objects like matrices and masked arrays, and assortment routines that makes array operations faster, which includes mathematical, logical, basic linear algebra, basic statistical operations, shape manipulation, input/output, sorting, selecting, discrete Fourier transforms, random simulation and many more operations.
Note: For more information, refer to NumPy in Python
Matplotlib.pyplot
Matplotlib is a plotting library of Python which is a collection of command style functions that makes it work like MATLAB. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits. Each #pyplot# function creates some changes to the figures i.e. creates a figure, creating a plot area in the figure, plotting some lines in the plot area, decoration of the plot with some labels, etc.
Note: For more information, refer to Pyplot in Matplotlib
Plotting the equation
Lets start our work with one of the most simplest and common equation Y = X². We want to plot 100 points on X-axis. In this case, the each and every value of Y is square of X value of the same index.
Python3
Here note that the number of points we are using in line plot(100 in this case) is totally arbitrary but the goal here is to show a smooth graph for a smooth curve and that’s why we have to pick enough numbers depending on the function. But be careful that do not generate too many points as a large number of points will require a long time for plotting.
Customization of plots
There are many pyplot functions are available for the customization of the plots, and may line styles and marker styles for the beautification of the plot.Following are some of them:
Function | Description |
---|---|
plt.xlim() | sets the limits for X-axis |
plt.ylim() | sets the limits for Y-axis |
plt.grid() | adds grid lines in the plot |
plt.title() | adds a title |
plt.xlabel() | adds label to the horizontal axis |
plt.ylabel() | adds label to the vertical axis |
plt.axis() | sets axis properties (equal, off, scaled, etc.) |
plt.xticks() | sets tick locations on the horizontal axis |
plt.yticks() | sets tick locations on the vertical axis |
plt.legend() | used to display legends for several lines in the same figure |
plt.savefig() | saves figure (as .png, .pdf, etc.) to working directory |
plt.figure() | used to set new figure properties |
Line Styles
Character | Line style |
---|---|
– | solid line style |
— | dashed line style |
-. | dash-dot line style |
: | dotted line style |
Character | Marker |
---|---|
. | point |
o | circle |
v | triangle down |
^ | triangle up |
s | square |
p | pentagon |
* | star |
+ | plus |
x | cross |
D | diamond |
Below is a plot created using some of this modifications:
Plotting Equations with Python in Matplotlib
In this article, we are going to cover the plotting of some basic equations in Python using matplotlib module. The goal is to plot a function in x i.e y = f(x). Example y = x 2 , y = x 2 +2x+3 , y = 2sin(x)+4 etc.
Before jumping directly on how to do this, let us learn the overview of how to plot these equations. Consider these points as a skeleton to the solution to this problem.
- Learn how to create a vector array using the NumPy library.
- Change and manipulate this vector to match the required equation.
- Plot this vector using the matplotlib library.
Now let’s start with the plotting of the simplest equation i.e y = x 2 .
Plotting y = x 2
As y is a function of x where each y (y1, y2, y3 ……….yn) is equal to the square of its x counterpart. So first we need to define an array x ranging from some initial point to a final point, for example [-10,10]. We will then calculate y array by squaring each element of the array x. This can be easily done with the help of NumPy. NumPy allows arithmetic operations on the NumPy arrays directly with ease. Look at the code below to plot the above function and try to understand the code by reading the comments.
# Importing the libraries import matplotlib.pyplot as plt import numpy as np # Creating the vector array x ranging from [-10,10] x = np.linspace(-10,10,100) # Manipulating the vector x to produce y=x^2 y = x**2 # Setting the figure size fig=plt.figure(figsize=(8,6)) #Plotting the matplotlib plot with x and y as parameters plt.plot(x,y,label='y = x^2',color='green') # Adding a grid plt.grid(alpha=.5,linestyle='-') # Naming the x and the y axis plt.xlabel('x-axis') plt.ylabel('y-axis') # Giving a title to the plot plt.title('Plotting a equation') # Adding the legend plt.legend() plt.show()
As you can see we follow the steps that I mentioned at the starting of the article. Let plot some more plots with the same method with slight variations.
Plotting y = Sin(x) + x
We can plot this graph using the same steps. See the code below which plot y = sin(x) + x in the range [-2*pi , 2*pi].
# Importing the libraries import matplotlib.pyplot as plt import numpy as np # Creating the vector array x ranging from [-2*pi,2*pi] x = np.linspace(-2*np.pi,2*np.pi,100) # Manipulating the vector x to produce y= sin(x)+x y = np.sin(x)+x # Setting the figure size fig=plt.figure(figsize=(8,6)) #Plotting the matplotlib plot with x and y as parameters plt.plot(x,y,label='y = sin(x)+x',color='red') # Adding a grid plt.grid(alpha=.5,linestyle='-') # Naming the x and the y axis plt.xlabel('x-axis') plt.ylabel('y-axis') # Giving a title to the plot plt.title('Plotting a equation') # Adding the legend plt.legend() plt.show()
Some cool graphs
Now let’s try some cool graphs with interesting equations. See the code below and read the comments to understand the equation and type of graph made.
# Importing the libraries import matplotlib.pyplot as plt import numpy as np # Creating the vector array x1 ranging from [-2*pi,2*pi] x1 = np.linspace(-2*np.pi,2*np.pi,100) # Manipulating the vector x1 to produce y1= sin(954x)-2cos(x) y1 = np.sin(954*x1)-2*np.cos(x1) # Creating the vector array x2 ranging from [0,3] x2 = np.linspace(0,3,100) # Manipulating the vector x2 to produce y2 = |Sin(x^x)/2^((x^x-pi/2)/pi)| y2 = abs((np.sin(x**x))/(2**((x**x-(np.pi/2))/np.pi))) # Setting the figure size fig=plt.figure(figsize=(12,12)) # Subplot 1 for x1 and y1 plt.subplot(2, 1, 1) plt.plot(x1, y1,label='y = sin(954x)-2cos(x)',color='red') plt.xlabel('x-axis') plt.ylabel('y-axis') plt.grid(alpha=.5,linestyle='-') plt.title('Plotting a equation') plt.legend() # Subplot 2 for x2 and y2 plt.subplot(2, 1, 2) plt.plot(x2, y2,label='y = |Sin(x^x)/2^((x^x-pi/2)/pi)|',color='green') plt.xlabel('x-axis') plt.ylabel('y-axis') plt.grid(alpha=.5,linestyle='-') plt.title('Plotting a equation') plt.legend() plt.show()
I hope you liked the article. Comment if you have any doubts or suggestions regarding this article.
You can also read other articles related to this. Click the links given below.