Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Mathematics LibreTexts

1.3: Plotting

( \newcommand{\kernel}{\mathrm{null}\,}\)

There are several packages for plotting functions and we will use the PyPlot package. Similar to the NumPy package, we must import the PyPlot package before we use it. We will use the alias plt. The first time you import PyPlot during a session, it will need to automatically download the package and install the dependencies.

1import matplotlib.pyplot as plt

output:

To actually plot a graph, we will also call the NumPy package so that we have access to the sin function.

1import numpy as np
2import matplotlib.pyplot as plt
3 
4x = np.linspace(0, 2*np.pi, 1000)
5y = np.sin(3*x)
6plt.plot(x, y, color='red', linewidth=2.0, linestyle='--')
7plt.title('The sine function');
8plt.show()

output:

clipboard_e3c98195c3f2ad8aaebb8058dc7e22990.png

Observe that, in the code above, we define the x-values we desire to be plotted using NumPy's linspace function. This function returns evenly spaced numbers over a specified interval. Here, we called for 1000 evenly-spaced numbers between 0 and 2pi. Then, we defined the y-values as a function of x. Here, we used y=sin(3x).

In the following example, we plot two functions, sin(3x) and cos(x) simultaneously.

01import numpy as np
02import matplotlib.pyplot as plt
03 
04x = np.linspace(0, 2*np.pi, 1000)
05y = np.sin(3*x)
06z = np.cos(x)
07plt.plot(x, y, color='red', linewidth=2.0, linestyle='--', label='sin(3x)')
08plt.plot(x, z, color='blue', linewidth=1.0, linestyle='-', label='cos(x)')
09plt.legend(loc='upper center');
10plt.show()

output:

clipboard_ee5fb4ea9f012d39abcd918e83e0f505a.png


1.3: Plotting is shared under a not declared license and was authored, remixed, and/or curated by LibreTexts.

  • Was this article helpful?

Support Center

How can we help?