Visualization with the matplotlib package¶

author: Parin Chaipunya affil: KMUTT

This notebook provides a short, hands-on demonstration of data visualization in Python using the matplotlib library, along with numpy for data generation.

From the complete matplotlib core library and backends that render the image, we import matplotlib.pyplot which handles most of the visualization tasks that we use.

In [1]:
import numpy as np
import matplotlib.pyplot as plt

Graph of a function of one variable (2D line plot)¶

The best way to learn this is through examples.

Example¶

Let us simply plot the graph of $f(x) = x\sin(x^{2})$ over the interval where $x \in [-5,5]$.

We start by defining the increments of $x$ and calculate $y = f(x)$ at these points.

In [2]:
x = np.linspace(-5,5,500)
y = x * np.sin(x**2)

Now that we have these points ready, we plot them using plt.plot. If we use the cammand prompt mode, plt.show() is also required.

It is usually a good practice to include plt.show() even in this ipynb format.

In [3]:
plt.plot(x,y)
plt.show()
No description has been provided for this image

We can also customize the plot to include the title, axis labels, etc.

In [4]:
plt.plot(x,y, 
         label='$f(x) = x \\sin(x^{2})$',
         color='indigo', 
         linewidth=2, 
         alpha=0.8)
plt.title('Graph of $f(x) = x \\sin(x^{2})$')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc='upper right')
plt.grid(True, linestyle=':', alpha=0.7)
plt.show()
No description has been provided for this image

Example¶

We can also plot multiple functions in one axis. Let us plot $f(x) = x \sin(x^{2})$ and $g(x) = x^{2}\cos(x)$ over the same interval as above.

In [5]:
x = np.linspace(-5,5,500)
y_f = x * np.sin(x**2)
y_g = x**2 * np.cos(x)

plt.plot(x,y_f, label='$f(x)$')
plt.plot(x,y_g, label='$g(x)$')
plt.title('The functions $f(x)$ and $g(x)$')
plt.legend()
Out[5]:
<matplotlib.legend.Legend at 0x7fc92836b750>
No description has been provided for this image

Subplots¶

We may plot multiple functions on different axes using subplot.

We need first to create a figure, then add to it the subplots.

In [6]:
fig = plt.figure(figsize=(10,4))
ax1 = fig.add_subplot(1,2,1)
ax1.plot(x,y_f)
ax1.set_title('The graph of $f(x)$.')

ax2 = fig.add_subplot(1,2,2)
ax2.plot(x,y_g)
ax2.set_title('The graph of $g(x)$.')

plt.tight_layout()
plt.show()
No description has been provided for this image

Graph of a function of two variables (3D surface plot)¶

We need an additional 3D toolkit.

In [7]:
from mpl_toolkits.mplot3d import Axes3D

Example¶

Let us now plot the function $f(x,y) = \dfrac{ \sin(\sqrt{ x^{2} + y^{2} }) }{ \sqrt{ x^{2} + y^{2} } }$.

First, we make the grids of $x$ and $y$ and calculate $z = f(x,y)$ on these grid poitns.

In [8]:
x = np.linspace(-5,5,500)
y = np.linspace(-5,5,500)
X, Y = np.meshgrid(x,y)

R = np.sqrt(X**2 + Y**2)
Z = np.sin(R) / R

Next, we continue with the plot. The first step is to create a figure and inside that, we create a 3D axis. After that, we create the surface and show the plot.

In [9]:
# Create a figure and an empty axis inside it.
fig = plt.figure(figsize=(10,3), constrained_layout=True)
ax = fig.add_subplot(111, projection='3d')

# Plot the surface inside the axis.
ax.plot_surface(X,Y,Z,
               cmap='coolwarm')

# Customization
ax.set_title('Surface of $f(x,y)$')
ax.set_xlabel('$x$ axis')
ax.set_ylabel('$y$ axis')
ax.set_zlabel('$z$ axis')
ax.zaxis.labelpad = 1 

# Show the surface.
plt.show()
No description has been provided for this image

Example¶

Let us also demonstrate 2x2 subplots containing the graphs of $f(x) = x \sin(x^{2})$, $g(x) = x^{2} \cos(x)$, $h(x,y) = \dfrac{ \sin(\sqrt{ x^{2} + y^{2} }) }{ \sqrt{ x^{2} + y^{2} } }$ and $k(x,y) = \dfrac{1}{4}x^{2} - 2xy + 2y^{2}$.

In [10]:
fig3 = plt.figure(figsize=(8,6))

x2d = np.linspace(-5,5,500)
y2d_f = x * np.sin(x**2)
y2d_g = x**2 * np.cos(x)

ax1 = fig3.add_subplot(2,2,1)
ax1.plot(x2d, y2d_f, color='red')
ax1.set_title('The graph of $f(x)$')

ax2 = fig3.add_subplot(2,2,2)
ax2.plot(x2d, y2d_g, color='blue')
ax2.set_title('The graph of $g(x)$')

x3d = np.linspace(-5,5,500)
y3d = np.linspace(-5,5,500)
X, Y = np.meshgrid(x3d,y3d)
R = np.sqrt(X**2 + Y**2)
Z_h = np.sin(R) / R
Z_k = .25*X**2 - 2*X*Y + 2*Y**2
ax3 = fig3.add_subplot(2,2,3, projection='3d')
ax3.plot_surface(X, Y, Z_h, cmap='plasma')
ax3.set_title('The graph of $h(x,y)$')

ax4 = fig3.add_subplot(2,2,4, projection='3d')
ax4.plot_surface(X, Y, Z_k, cmap='plasma')
ax4.set_title('The graph of $k(x,y)$')

plt.tight_layout(pad=3.0)
plt.show()
No description has been provided for this image