Author avatar

Vivek Kumar

Working with Toolkit

Vivek Kumar

  • Apr 10, 2019
  • 10 Min read
  • 27 Views
  • Apr 10, 2019
  • 10 Min read
  • 27 Views
Data
matplotlib

Introduction

In this guide, we will learn about the extended functionality of the Matplotlib which includes:

  1. axes_grid1 toolkit: Used to control the layout of the plots.
  2. axisartist toolkit: Used to control the properties of curved coordinate systems.
  3. mplot3d toolkit: Used to generate the 3D plots.

The Baseline

In the guide, we are going to use the following libraries:

Syntax:

1
2
3
4
5
6
7
# Importing necessary libraries
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
from mpl_toolkits.mplot3d import Axes3D
python

Axes_grid1 Toolkit

As per the Matplotlib documentation:

axes_grid1 is a collection of helper classes to ease displaying (multiple) images with matplotlib.

The table given below lists available helper classes inside axes_grid1:

ClassPurpose
ImageGrid, RGB Axes and AxesDividerAdjusts the location of (multiple) Axes
ParasiteAxesPlots different data (e.g., different y-scale) in a same Axes
AnchoredArtistsPlots an artist at some specific position like legend

Let us learn about ImageGrid and ParasiteAxes classes one by one with some data.

1. ImageGrid

Consider if you want to display four images with given constraints:

  1. Have a given aspect ratio.
  2. Images have same size.
  3. Images should have a fixed padding among them.
  4. The axes size is not defined in the normalized figure coordinates.

Such a scenario can be easily solved with ImageGrid. Let us generate some random data for four images and learn to plot them using ImageGrid:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Initializing the data
im = np.linspace(0, 1000, 100).reshape((10, 10))

# Defining figure number with size
fig = plt.figure(0, (4., 4.))

# Establishing ImageGrid
grid = ImageGrid(fig, 111,              # Size of each subplot
                 nrows_ncols=(2, 2),    # A 2x2 grid of axes
                 axes_pad=0.2)          # Pads 0.2 inches between axes
                 
# Plotting
for count in range(4):
    grid[count].imshow(im, cmap='copper')  

# Displaying the plot
plt.show()
python

ImageGrid

2. ParasiteAxis

The ParasiteAxis provides two solutions to day-to-to visualization problems through its twinx and twin axes.

The twinx axes helps to put two different value graphs on the same figure where, for instance, bottom and left axes are assigned to first graph and the bottom and right axes are assigned to the second graph. This is possible using the host_subplot and its derivative twinxmethod. Let us learn this using the energy consumed in a house and amount of cost associated with the energy utilized:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Setting the twinx system
host = host_subplot(111)
par = host.twinx()

# Initializing the data
energy = np.array([12, 18, 2, 32, 16])
cost = energy * np.array([5, 5.2, 3.2, 4, 5])

# Plotting
p1, = host.plot(np.arange(1, 6), energy, label="Energy consumed (in kWh)")
p2, = par.plot(np.arange(1, 6), cost, label="Amount spent (in USD)")

# Labelling
host.set_xlabel("Days")
host.set_ylabel("Energy consumed (in kWh)")
par.set_ylabel("Amount spent (in USD)")

leg = plt.legend()

host.yaxis.get_label().set_color(p1.get_color())
leg.texts[0].set_color(p1.get_color())

par.yaxis.get_label().set_color(p2.get_color())
leg.texts[1].set_color(p2.get_color())

plt.title('Twinx', weight='bold', fontsize=20)

# Displaying the plot
plt.show()
python

Twinx

On the other hand, we have twin axes which means that a certain figure can have two different values given to the x-axis or y-axis.

For instance, consider two currencies C1 and C2, where C2 = 5*C1. A person buys five motorcycles using currency C1, now let us plot the graph with the purchasing cost of these five vehicles using both the currencies:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Setting the twin system
ax = host_subplot(111)

# Initializing the data
C1 = np.array([12000, 15000, 10000, 25000, 22000])
C2 = C1 * 5

# Plotting purchase cost for five days  
ax.scatter(C1, np.arange(1, 6), s=200)

# Setting C1 label
ax.set_xlabel('C1', fontsize=18)
ax.xaxis.set_label_coords(1.05, 0.00)

# Defining and labelling twin axis 
ax2 = ax.twin()  
ax2.set_xticks(C1)
ax2.set_xticklabels(C2)
ax2.set_xlabel('C2', fontsize=18)
ax2.xaxis.set_label_coords(1.05, 1.02)

# Adjusting right and top axes
ax2.axis["right"].major_ticklabels.set_visible(False)
ax2.axis["top"].major_ticklabels.set_visible(True)

# Displaying the title
plt.title('Twin', weight='bold', fontsize=20, y=1.05)

# Displaying the plot
plt.show()
python

Twin

Axisartist Toolkit

As per the Matplotlib documentation:

The axisartist contains a custom Axes class that is meant to support curvilinear grids.

Let us learn the implementation of Axisartist Toolkit by extending our Twinx system example. We already have the utilized cost and amount presented in the figure. Let us extend it by adding a third parameter: number of appliances in use. Using Axisartist toolkit we can create an additional parasite axis to represent our third parameter:

Axisartist

Axisartist provides many other important axis functionalities which includes:

  • Changing the color of tick labels using the major_ticklabels.set_color() method.
  • Making tick labels invisible using the major_ticklabels.set_visible() method.
  • Controlling the visibility of ticks, tick labels, and label just by using a single method, toggle().
  • Rotating the tick labels using the major_ticklabels.set_axis_direction() method.

Mplot3d Toolkit

The mplot3d toolkit provides the feasibility for the construction of three-dimensional plots. Let us learn this toolkit by constructing given 3D plots:

  1. 3D Line plot
  2. 3D Scatter plot
  3. 3D Bar plot
  4. 3D Subplotting with text

1. 3D Line Plot

Let us consider some random data generated using NumPy and plot it while importing Axes3D from the mplot3d module:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Setting the figure size
fig = plt.figure(figsize=(8, 5))

# Initializing the data
theta = np.linspace(-10 * np.pi, 10 * np.pi, 100)
z = np.linspace(-1, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

# Plotting
ax = fig.add_subplot(111, projection='3d')
ax.plot(x, y, z, label='Curve')
ax.legend()

# To save
fig.savefig('curve.png',dpi=96)

# Displaying the plot
plt.show()
python

Curve

2. 3D Scatter Plot

To draw a 3D scatter plot, we will again take some random data and plot it as shown:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Setting the figure size
fig = plt.figure(figsize=(8, 5))

# Initializing data and axis
np.random.seed(42)
colors = ['Red', 'Green']
markers = ['*', '^']

ax = fig.add_subplot(111, projection='3d')

# Plotting
for i in range(100):
    val = np.random.randint(2)
    x, y, z = np.random.rand(3)
    ax.scatter(x, y, z, c=colors[val], marker=markers[val])

# Labelling
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

# Saving the figure
fig.savefig('scatter.png',dpi=96)

# Displaying the plot
plt.show()
python

Scatter

3. 3D Bar Plot

To plot 3D bar plot, we are taking four variables and assigning them some random values as shown:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Setting the figure size
fig = plt.figure(figsize=(8, 5))

# Initializing data and axis
np.random.seed(42)
colors = ['r', 'g', 'b', 'y']
yticks = [3, 2, 1, 0]

ax = fig.add_subplot(111, projection='3d')

# Plotting
for c, k in zip(colors, yticks):    
    x = np.arange(10)
    y = np.random.rand(10)
    
    # Keeping all the bars on same Y-tick with similar color 
    cs = [c] * len(x)

    # Keeping 80% opacity.
    ax.bar(x, y, zs=k, zdir='y', color=cs, alpha=0.8)

# Labelling
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

# Saving the figure
fig.savefig('bar.png',dpi=96)

# Displaying the plot
plt.show()
python

bar

4. 3D Subplotting with Text

Let us plot the above bar chart as the first subplot and a text in the second 3D subplot:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Setting the figure size
fig = plt.figure(figsize=(10, 5))

# =============
# First Subplot
# =============

# Initializing data and axis
np.random.seed(42)
colors = ['r', 'g', 'b', 'y']
yticks = [3, 2, 1, 0]

ax = fig.add_subplot(121, projection='3d')

# Plotting
for c, k in zip(colors, yticks):    
    x = np.arange(10)
    y = np.random.rand(10)
    
    # Keeping all the bars on same Y-tick with similar color 
    cs = [c] * len(xs)

    # Keeping 80% opacity.
    ax.bar(x, y, zs=k, zdir='y', color=cs, alpha=0.8)

# Labelling
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

# =============
# Second Subplot
# =============

# Labelling text in the 3D surface
ax = fig.add_subplot(122, projection='3d')
ax.text(0, 0, 0.5, "Text in the 3D surface", color='g', weight='bold', fontsize=15)

# Saving the figure
fig.savefig('subplot.png',dpi=96)

# Displaying the plot
plt.show()
python

Text

Conclusion

In this guide, you have learned about the three most important Matplotlib toolkits: axes_grid1, axisartist, and mplot3d.

To learn more on Matplotlib you can refer the following guides:

0