How to plot a 2d graph using python? in this post, we are going to use the library function matplotlib for creating static, animated graphs and visualization of mathematical figures using 2d and 3d graphs.
Table of Contents
- How to install Numpy, matplotlib packages?
- Why do we use the Numpy module?
- Sin x, Cos x, and exponential In numpy module
- Legends Labels and Titles
- How to set colors, line widths, linestyle, and markers?
- Plot range
- Subplots
- Text annotation
How to install Numpy, matplotlib packages?
python -m pip install -U pip setuptools
python -m pip imstall matplotlib
Python
To use Matplotlib in a python program, you can import all functions from pylab.
>>>from pylab import*
In order to plot a 2D graph we can use the plot function from matplotlib. Plot function plots the provided data. But the display work is done by the show() function.
Why do we use the Numpy module?
It has two useful functions i.e., arange and linspace. We can generate vectors by using these two functions.
np.arange(start, end, step):- It returns evenly spaced values with a given step within a given interval [start, end]
- np.arange(0, 1, 0.2) gives [0, 0.2, 0.4, 0.6, 0.8]
- np.arange(0, 100, 0.1) gives [0, 0.01, 0.02, …………,99.8, 99.9]
np.arange(start, end, subintervals):- It returns spaced numbers over a specified interval [start, end] in a given number of subintervals.
- np.linspace(0, 1, 5) gives [0, 0.25, 0.50, 0.75, 1]
- np.linspace(0, 1, 100) gives [0, 0.01, 0.02, …….,0.98, 0.99]
Example 1: Plot the graph of f(x)= x2 in [0, 5]
from pylab import*
import numpy as np
x = np.linspace(0, 5, 10)
y = x**2
plot(x,y)
show()
Python
Output

Example 2: Plot the graph of f(x)= x3 in [-5, 5]
from pylab import*
import numpy as np
x= np.linspace(-5, 5, 100)
y= x**3
plot(x,y)
show()
Python
Output

Example 3: Plot the graph of f(x)= x2 and g(x)= x3 in [-1, 1]
from pylab import*
import numpy as np
x= np.linspace(-1, 1, 100)
f= x**2
g= x**3
plot(x,f)
plot(x,g)
show()
Python
Output

Sin x, Cos x, and exponential In numpy module
Now we are heading toward trigonometric functions such as sin x, cos x, ex, etc. All these functions are available in numpy module.
Trigonometric function | Python Version |
---|---|
sin x | np.sin(x) |
cos x | np.cos(x) |
ex | np.exp(x) |
Example 4: Plot the graph of f(x) =sin x in [-2pi, 2pi]
from pylab import*
import numpy as np
x= np.linspace(-2*pi, 2*pi, 100)
f=np.sin(x)
plot(x,f)
show()
Python
Output

Example 5: Plot the graph of f(x)= ex in [-10, 10]
from pylab import*
import numpy as np
x= np.linspace(-10, 10, 100)
y= np.exp(x)
plot(x,y)
show()
Python
Output

Example 6: Plot the graph of f(x)= 1+x+2x2+3x3+4x4 in [-10, 10]
from pylab import*
import numpy as np
x= np.linspace(-10, 10, 100)
y= 1+x+2*x**2+3*x**3+4*x**4
plot(x,y)
show()
Python
Output

Legends Labels and Titles
Till now we have learned how to create graphs. Now we are going to make them more attractive by using titles, axis labels, and legends.
- We use the title attribute after plotting and it is written in LATEX.
- For axis labels, we use xlabel and ylabel
- After the label, you can use legend(). It is used to describe an area on the graph that includes all the elements of a graph.
Example 7: Plot the graph of f(x)= x in [0, 5]
from pylab import*
import numpy as np
x= np.linspace(0, 5, 10)
y= x**2
plot(x,y, label ="$y=x^2$")
xlabel('x-axis')
ylabel('y-axis')
legend()
show()
Python
Output

Example 8: Plot the graph of f(x) = sin x and g(x) = cos x in [-2pi, 2pi]
from pylab import*
import numpy as np
from math import*
x = np.linspace(-2*pi, 2*pi, 100)
f = np.sin(x)
g = np.cos(x)
plot(x,f, label="$\sin x$")
plot(x,g, label="$\cos x$")
xlabel('x-axis')
ylabel('y-axis')
title('graph of $f(x)=\sin x$ and $g(x)=\cos x$')
legend()
show()
Python
Output

The legend function takes an optional argument loc that can be used to specify the location of the legend.
Python Code | Location of legend |
---|---|
legend(loc=1) | upper right corner |
legend(loc=2) | upper left corner |
legend(loc=3) | lower right corner |
legend(loc=4) | lower left corner |
legend(loc=0) | matplotlib decides the optimal location |
Example 9: Plot the graph of f(x)= 1/x in [-5, 5]
from pylab import*
import numpy as np
x = np.linspace(-5,5,100)
y= 1/x
plot(x,y, label="$y=1/x$")
xlabel('x-axis')
ylabel('y-axis')
title('graph of $f(x)=1/x$')
legend(loc=4)
show()
Python
Output

Example 10: Plot the graph of f(x) = 1+1/x+1/x2 in [-5,5]
from pylab import *
import numpy as np
x = np.linspace(-5,5,100)
y = 1+1/x+1/x**2
plot(x,y, label="$y=1+1/x+1/x^2$")
xlabel('x')
ylabel('y')
title('$y=1+1/x+1/x^2$')
legend()
show()
Python

Example 11: Plot the graph of f(x) = xsin(1/x2) in [-5,5]
from pylab import*
import numpy as np
x = np.linspace(-5,5,100)
y= x*np.sin(1/x**2)
plot(x,y, label="$y= xsin (1/x^2)$")
xlabel('x')
ylabel('y')
title('$y= xsin (1/x^2)$')
legend()
show()
Python
Output

How to set colors, line widths, linestyle, and markers?
Now we are going to see how to set colors, line widths, and different line styles to the graph. For line widths, you can use the keyword lw or you can also use linewidth.
Colors that you can use
Color | Name |
---|---|
‘y’ | yellow |
‘m’ | magenta |
‘c’ | cyan |
‘r’ | red |
‘g’ | green |
‘b’ | blue |
‘w’ | white |
‘k’ | black |
Line style that you can use
For line style, you can use the keyword linestyle or ls.
Line style | Name |
---|---|
– | solid line |
— | dashed line |
…….. | dotted line |
-. | dash-dot line |
Markers that you can use
Marker | Name |
---|---|
o | Circle |
+ | Plue sign |
* | Asterisk |
. | Point |
x | Cross |
– | Horizontal line |
_ | Vertical line |
s | Square |
d | Diamond |
^ | Upper-pointing triangle |
v | Downward-pointing triangle |
p | pentagram |
h | hexagram |
Example 12: Plot the graph of f(x) = log x in [0,10]
from pylab import *
import numpy as np
x = np.linspace(0,10,100)
y= np.log(x)
plot(x,y,'r')
xlabel('x')
ylabel('y')
title('$y = \log x$')
show()
Python
Output

Example 13: Plot the graph of f(x) = x4 in [0,5] with the red dashed line with circle markers
from pylab import*
import numpy as np
x = np.linspace(0, 5, 10)
y = x**4
plot(x, y, "ro--",label="$f(x) = x^4$")
xlabel('x')
ylabel('y')
title('graph of $y = x^4$')
legend()
show()
Python
Output

Example 14: Plot the graph of f(x) = e-x^2 in [-5,5] with a green dashed points line with an upward-pointing triangle
from pylab import *
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.exp(-x**2)
plot(x, y, "g-.^", label="$f(x) = e^{-x^2}$")
xlabel('x')
ylabel('y')
title('Graph of $y = e^{-x^2}$')
legend()
show()
Python
Output

Example 15: Plot the graph of f(x) = ex sin(x) in [-5pi, 5pi] with blue points line with upward-pointing triange
from pylab import *
import numpy as np
from math import *
x = np.linspace(-5*pi, 5*pi, 100)
y = np.exp(x)*np.sin(x)
plot(x, y, "b^:", label="$y=e^x \sin(x)$")
xlabel('x')
ylabel('y')
title('graph of $y=e^x \sin(x)$')
legend()
show()
Python
Output

Plot range
If you want to specify the ranges of the x-axis and y-axis then you can also do this in python. All you need to do is just use xlim([value1, value2]) for the x-axis and ylim([value1, value2]) for the y-axis. We generally use them to fixed axes ranges.
Example 16: Plot the graph of f(x) = x in [0, 5] and take the plot range x-axis [2,4]
from pylab import *
import numpy as np
x = np.linspace(0, 5, 10)
y = x**4
plot(x, y, "r--", label="$y=x^4$")
xlabel('x')
ylabel('y')
xlim([2,4])
title("graph of $y=x^4$")
legend()
show()
Python
Output

Subplots
When it comes to making multiple graphs in one figure object, in a single cell we use the subplots. subplot(r,c,n) function is used to insert the graph at the nth position in the r x c table. Here we use separate legend() for each subgraph.
Example 17: Plot the graph of sin(x), cos(x), ex and x2 in [0,5] in one figure with (2×2) subplots
from pylab import *
import numpy as np
from math import *
x = np.linspace(0,5,10)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.exp(x)
y4 = x**2
subplot(2,2,1)
plot(x,y1, 'r--o', label="$y1=\sin(x)$")
legend()
subplot(2,2,2)
plot(x,y2, 'b--o', label="$y2=\cos(x)$")
legend()
subplot(2,2,3)
plot(x,y3, 'g--o', label="$y3=e^x$")
legend()
subplot(2,2,4)
plot(x,y4, 'c--o', label="$y4= x^2$")
legend()
show()
Python
Output

Example 18: Plot the graph of ex, e-x, e1/x in [0,5] in one frame with (3×1) subplots
from pylab import *
import numpy as np
from math import *
x = np.linspace(0,5,10)
y1 = np.exp(x)
y2 = np.exp(-x)
y3 = np.exp(1/x)
subplot(3,1,1)
plot(x,y1, 'r--o', label="$y1 = e^x $")
legend()
subplot(3,1,2)
plot(x,y2, 'c--o', label="$y2 = e^{-x}$")
legend()
subplot(3,1,3)
plot(x,y3, 'g--o', label="$y3 = e^{1/x}$")
legend()
show()
Python
Output

Text annotation
Using the text function text(xvalue, yvalue, text, font size, color), we can easily denote the location of text, color, and text’s font size.
Example 19: Plot the graph of f = x2 and g = x3 in [-1,1]
from pylab import *
import numpy as np
x = np.linspace(-1,1,1000)
f = x**2
g = x**3
plot(x,f, 'r--', label="$f(x) = x^2$")
plot(x,g, 'g--', label="$g(x) = x^3$")
text(0.15, 0.2, "$f(x) = x^2$", fontsize=10, color="blue")
text(0.65, 0.1, "$g(x) = x^3$", fontsize=10, color="blue")
xlabel('x')
ylabel('y')
legend()
show()
Python
Output

Here we are finishing our post on “How to plot 2d graph using python”, in this post we have seen different types of graphs and different functions that makes the graph more attractive.
Note: If you are facing an error in compiling these codes kindly use trinket.io
Also Read: Trapezoidal Method Python Program