7. Matplotlib

7. Matplotlib#

7.1 Introduction#

Welcome to the fascinating world of matplotlib! Matplotlib is a powerful Python module that empowers you to create impressive visualizations. If you’re tired of basic graphs in Excel, matplotlib is your gateway to a new level of creativity and versatility. With it, you can bring your data to life by crafting captivating graphs that effectively communicate your insights. In this section, you’ll learn how to harness the power of matplotlib to create visually appealing and engaging graphs.

We first start by importing it:

import matplotlib.pyplot as plt

The most frequently used functions in matplotlib are summarized in the table below:

Function

Description

Usage

plt.figure( )

Create a new figure or activate an existing figure

plt.figure()

plt.subplot( )

Create subplots within a figure

plt.subplot(num_rows, num_cols, plot_index)

plt.plot( )

Create line plot or scatter plot

plt.plot(x, y, options)

plt.title( )

Set the title of the current axes

plt.title(‘Title’)

plt.suptitle( )

Set the super title of the entire figure

plt.suptitle(‘Super Title’)

plt.xlabel( )

Set the label for the x-axis

plt.xlabel(‘X-axis label’)

plt.ylabel( )

Set the label for the y-axis

plt.ylabel(‘Y-axis label’)

plt.xlim( )

Set the limits for the x-axis

plt.xlim(x_min, x_max)

plt.ylim( )

Set the limits for the y-axis

plt.ylim(y_min, y_max)

plt.legend( )

Add a legend to the plot

plt.legend()

plt.grid( )

Display grid lines on the plot

plt.grid(True/False)

plt.show( )

Display the figure

plt.show()

plt.close( )

Close the figure window

plt.close()

Below is an example to illustrate how to use these functions professionally. We will utilize numpy and matplotlib to generate multiple plots in a single figure. We create four subplots, each representing a different type of graph. In the first subplot, we create a line plot of the sine function, while in the second subplot, we display a line plot of the cosine function. Moving on to the third subplot, we generate a scatter plot of randomly generated points. Lastly, in the fourth subplot, we create a line plot with a filled area between the sine and cosine functions.

To enhance the visual appeal, we customize each plot with titles, axis labels, and legends. Finally, we display the figure, presenting our multiple plots in an engaging and visually appealing manner.

import numpy as np

x = np.linspace(0, 2 * np.pi, 100)
y_sin = np.sin(x)
y_cos = np.cos(x)

plt.figure(figsize=(10, 8))

plt.subplot(2, 2, 1)
plt.plot(x, y_sin, label='sin(x)')
plt.title('Sine Function')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()

plt.subplot(2, 2, 2)
plt.plot(x, y_cos, label='cos(x)', color='r', linestyle='--')
plt.title('Cosine Function')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()

plt.subplot(2, 2, 3)
x_points = np.random.rand(20) * 2 * np.pi
y_points = np.random.rand(20) - 0.5
plt.scatter(x_points, y_points, color='g', label='Points')
plt.title('Scatter Plot')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()

plt.subplot(2, 2, 4)
plt.plot(x, y_sin, label='sin(x)', color='b', linestyle='-.')
plt.plot(x, y_cos, label='cos(x)', color='r', linestyle=':')
plt.fill_between(x, y_sin, y_cos, where=(y_sin >= y_cos), interpolate=True, alpha=0.3, color='purple')
plt.fill_between(x, y_sin, y_cos, where=(y_sin <= y_cos), interpolate=True, alpha=0.3, color='orange')
plt.title('Fill Between Lines')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()


plt.suptitle('Multiple Plots')
plt.tight_layout()

plt.show()
../../_images/835b8f8c9b5c6623e63cb6da0e2af35d214f0e22d473bf582725b1f0c3f4d0d3.png

Below is an example to illustrate the difference between plots that use the plt.grid( ) function:

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(6, 4))

plt.subplot(2, 1, 1)
plt.plot(x, y)
plt.title('Line Plot with Grid')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)

plt.subplot(2, 1, 2)
plt.plot(x, y)
plt.title('Line Plot without Grid')
plt.xlabel('x')
plt.ylabel('y')

plt.tight_layout()

plt.show()
../../_images/0fd525f7b582cfa822bfdb8b980403576453ec16fea4214fcfb437839b4ea659.png

3D plots#

Matplotlib can also create 3D plots. Below is a simple example. You can try to plot different functions, larger ranges, or anything you want.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

theta = np.linspace(0, 2 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, projection='3d')

ax.plot(x, y, z, label='3D Curve', linewidth=2)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D Plot')
ax.legend()

ax.grid(True)

ax.view_init(elev=25, azim=30)

plt.show()
../../_images/b1d7dbc798ebcd7cae083b7e0c2d20fddebd14ebd6830faecc9d04c2a9f7fa88.png