Skip to main content

Plotting with Matplotlib

Matplotlib is a Python library used for visualizing data. It is an extensive library and sub-modules like pyplot provides functionality equivalent to Matlab.

Let's start by understanding few basic components :-

Figure : Figure is the top level window or container that everything is drawn upon.

Axes : Axes is the area on which we plot the data and will have associated labels and ticks.

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

fig = plt.fig()
ax = plt.axes()
plt.show()

Above code will create a new container (figure) and add an axes. We use the call plt.show() to visualize the plot. If you notice, it will be an empty bounding box with ticks (this empty box is axes). A figure can have multple axes. Axes can have 2 (X-Axis and Y-Axis) or 3 Axis objects. (3 in case of 3D)

Axis : Axis is a number line object which takes care of graph limits and generating the ticks.

A typical plot will start with a figure, then axes will be added to it followed by a call to one of the plotting method. There are two commonly used methods - plot and scatter. Plot draw points with line connecting them, while scatter draws unconnected points.

Plot Example

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

fig = plt.figure()
# Add axes using add_subplot - 1 row and 1 column on grid
ax = fig.add_subplot(111)

# Use plot method from Axes object to plot data passed using X & Y (linear data)
ax.plot([0,1,2,3,4], [0,10,20,30,40], color='blue',  linewidth=2)

# Set the limit, label on X & Y Axis
ax.set_xlim([-1,5])
ax.set_ylim([-5,50])
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_title('Example Plot')
plt.show()


Scatter Example

In this example scatter method is called from the axis object, which draws unconnected points.

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter([0,1,2,3,4], [0,10,20,30,40])
plt.show()


Pyplot methods & Axes methods

In our examples above, we have used the methods from Axes object, whereas we can also use the methods from Pyplot as well. Infact, all the Axes methods exist with Pyplot and behind the scenes will be tranformed to call one of the method from Axes object.

In the example below, we are achieving plotting the same plot using pyplot methods.

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

plt.plot([0,1,2,3,4], [0,10,20,30,40], color='red',  linewidth=2)
plt.xlim(-1,5)
plt.ylim(-5,50)
plt.scatter([0,1,2,3,4], [0,10,20,30,40])
plt.show()

Comments