Getting Started with Matplotlib


Matplotlib

In this section, we'll give a brief introduction to the Matplotlib module which is one of the most popular Python packages used for data visualization.

Plot

The first function we introduce is plot, which allows you to plot 2D data.
import numpy as np
import matplotlib.pyplot as plt

# We plot the graph of y = x^2
x = np.arange(-10, 10) # x coordinate
y = x**2 # y coordinate

plt.plot(x, y) # Plot the graph
plt.show()  # You need to call plt.show() to show the plotted graph

Multiple Functions

We can also plot multiple functions in the same graph, and add a title, legend, and axis labels:
import numpy as np
import matplotlib.pyplot as plt

# Create the x and y coordinates
x = np.arange(-10, 10) 
y1 = x**2 
y2 = x**3

# Plot multiple functions
plt.plot(x, y1)
plt.plot(x, y2)
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('introduction to matplotlib')
plt.legend(['x^2', 'x^3'])
plt.show()

Subplot

Sometimes we want to can plot different funtions in the different plot but in the same figure, in this case we can use the subplot function.
import numpy as np
import matplotlib.pyplot as plt

# subplot(nrows, ncols, plot_number)
# Arugments are number of rows and colums of the plot 
# and the active plot number

# Create the x and y coordinates
x = np.arange(-10, 10) 
y1 = x**2 
y2 = x**3

# Create a subplot grid with 1 row and 2 colums
# and set the active plot number to 1
plt.subplot(1, 2, 1)

# Make the first plot at the active plot 
plt.plot(x, y1)
plt.title('x^2')

# Set the active plot number and make the second plot
plt.subplot(1, 2, 2)
plt.plot(x, y2)
plt.title('x^3')

# Show the figure.
plt.show()

Imshow

You can also use the imshow function to show images.
import numpy as np
from cv2 import imread
import matplotlib.pyplot as plt

img = imread('cat.jpg')

# Plot the image
plt.imshow(img)

# Imshow works better if the data is with type unit8, here we 
# cast the image to uint8 explicitly.
plt.imshow(np.uint8(img))

# Show the image
plt.show()