Starting off with Visualization in Python — Matplotlib
By: Pranav Prathvikumar
Tags: Python, Data Science, Visualization, Data Visualization

First step as always is to import all the required libraries.

import matplotlib.pyplot as plt

import numpy as np

from random import sample

%matplotlib inline

Lets generate some data for the plotting exercise and plot a simple line plot.

x = np.linspace(0,10,20)#Generate 20 points between 0 and 10

y = x**2 # Create y as X squared

plt.plot(x,y) # Plot the above data

Figure 1

Plotting the above figure requires only a single line command. While it is simple, it does not mean we don’t have the option to customize it.

plt.plot(x, y, color='green', linestyle='--',

linewidth=2, alpha= 0.5)

Figure 2

The parameters passed within the plot command control for:

‘color’ indicates the colour of the line and can be given even as a RGB hex code ‘linestyle’ is how you want the line to be, can be ‘ — — ’ or ‘-.’ for dash dotted line ‘linewidth’ takes an integer input for indicating the thickness of the line ‘alpha’ controls the transparency of the line

Sometimes a line might not be enough, you might need to even indicate which are the exact data points, in such cases you can add markers

plt.plot(x, y, marker = 'o', markerfacecolor = 'red', markersize = 5)

Fig 3

This plot has red coloured round markers. These markers can further be customized by modifying their boundaries.

plt.plot(x, y, marker = 'o', markerfacecolor = 'red', markersize = 10, markeredgewidth = 2, markeredgecolor = 'black')

Fig 4

The markers are same as before, but now they have a black boundary.

The parameters for controlling the markers are:

‘marker’ indicates what shape you want the marker to be, can be ‘o’ ,‘*’ or ‘+’ ‘markerfacecolor’ indicates the colour of the marker ‘markersize’ similar to linewidth controls the size of the marker ‘markeredgewidth’ and ‘markeredgecolor’ are used for specifying the boundary thickness and colour respectively.

Lets combine all of the above together into one plot:

Figure 5

Not the prettiest of plots, but you get the idea.

While this covers the basics of plotting data, there is still a lot more to be done is terms of titles, range of axes, legends etc.

The easiest way to do this is via the use of Matplotlib’s object oriented method.

Object Oriented method

Matplotlib has an object oriented API which allows you to create figure and axes objects. These objects can then be called in an orderly manner to perform functions such as plotting the data or customizing the figure.

fig, ax = plt.subplots()

Fig 6

The above command returns the figure and axis objects and creates an empty plot.

This can then be used to recreate the above plot with the plot and axes titles and the legend.

fig, ax = plt.subplots()#Create the objects

ax.plot(x,y,label = 'X squared')#The data to be plotted and legend

ax.set_title('Plot 1')#Plot title

ax.set_xlabel('X')#X axis title

ax.set_ylabel('Y')#Y axis title

ax.set_xlim(0,10)#Range of X axis

ax.set_ylim(0,110)#Range of Y axis

plt.legend()#Command to display the legend

Fig 7

The above plot(Fig 7) has the axes and plot titles, legend and different ranges for the X and Y axes.

Plotting Multiple lines

Suppose you want to compare two different sets of data, i.e, by plotting multiple lines in the same figure. In that case all you need to add is one more plot command.

fig, ax = plt.subplots()#Create the objects

ax.plot(x,y,label = 'X squared')#The data to be plotted and legend

ax.plot(x,x**3,label = 'X cubed')#The data to be plotted and legend

ax.set_title('Plot 1')#Plot title

ax.set_xlabel('X')#X axis title

ax.set_ylabel('Y')#Y axis title

ax.set_xlim(0,10)#Range of X axis

ax.set_ylim(0,110)#Range of Y axis

plt.legend()#Command to display the legend

Fig 8

Another way of comparing would be to show two different plots side by side.

fig, ax = plt.subplots(1,2)#Create the objects

ax[0].plot(x,y,label = 'X squared')#The data to be plotted and legend

ax[1].plot(x,x**3,label = 'X cubed')#The data to be plotted and legend

ax[0].set_title('Plot 1')#Plot title

ax[1].set_title('Plot 2')#Plot title

ax[0].legend()#Command to display the legend for plot 1

ax[1].legend()#Command to display the legend for plot 2

plt.tight_layout()#To ensure no overlap

Fig 9

This is done by first passing in the number of plots in the ‘subplot()’ function. The (1,2) above means that there should be 1 row of plots and 2 columns of plots, in effective meaning 2 plots. The functions are repeated for each one of the plots and the ‘tight_layout()’ command ensures that there is no overlap. A small change here being the command to display the legends. The plot.legend() function displays the legend only for one plot, to display for both you need to specify it for each plot.

The third way of comparison would be to use an inset plot. Within a larger plot, have a smaller plot.

fig, ax = plt.subplots(figsize = (12,4))

axins = ax.inset_axes([0.1,0.6,0.4,0.3] )#Left, Bottom, Width, Height ax.plot(x,y,label='X squared')# Main plot

axins.plot(x,1/x,label='X inverse')# Inset plot ax.set_xlabel('X')#X axis title

ax.set_ylabel('Y')#Y axis title

axins.set_xlabel('X')#X axis title

axins.set_ylabel('Y')#Y axis title ax.set_title('Main Plot')#Main plot title

axins.set_title('Inset Plot')# Inset plot title

ax.legend()#Legend for main plot

axins.legend()#Legend for inset plot

Fig 10

The ‘figsize’ parameter within the ‘subplots()’ function allows to change the size of the figure. The ‘inset_axes’ function is used to create the inset plot while also specifying the location and size. The first two numbers specify the plot location in terms of percentage. In the above case, the first two numbers 0.1 and 0.6 specifies that the plot should be 10% to the left and 60% above the Y and X axes respectively. The last two numbers 0.4 and 0.3 specifies that the plot should be 40% and 30% of the main plot’s width and height.

You might have noticed that the legend of the main plot is overlapping on the inset plot. While matplotlib automatically chooses the best possible location for the legend, it can be manually moved as well using the ‘loc’ parameter.

fig, ax = plt.subplots(figsize = (12,4))

axins = ax.inset_axes([0.1,0.6,0.4,0.3] )#Left, Bottom, Width, Height ax.plot(x,y,label='X squared')

axins.plot(x,1/x,label='X inverse') ax.set_xlabel('X')#X axis title

ax.set_ylabel('Y')#Y axis title

axins.set_xlabel('X')#X axis title

axins.set_ylabel('Y')#Y axis title ax.set_title('Main Plot')

axins.set_title('Inset Plot')

ax.legend(loc = 4)

axins.legend()

Fig 11

The ‘loc’ parameter takes in input between 0 and 10 corresponding to a position within the plot. 0 means that Matplotlib will choose the best possible position and it is the default option with all other integers corresponding to a location within the plot. Here I passed ‘4’ to the ‘loc’ parameter meaning the legend is placed in the bottom right corner.

The last customization I will be covering will be with changing the plot background.

fig, ax = plt.subplots(figsize = (12,4))

axins = ax.inset_axes([0.1,0.6,0.4,0.3] )#Left, Bottom, Width, Height ax.plot(x,y,label='X squared')

axins.plot(x,1/x,label='X inverse') ax.set_xlabel('X')#X axis title

ax.set_ylabel('Y')#Y axis title

ax.grid(True)#Show grid

axins.set_xlabel('X')#X axis title

axins.set_ylabel('Y')#Y axis title

axins.grid(color='blue', alpha=0.3, linestyle='--', linewidth=2)#Grid modifications ax.set_title('Main Plot')

axins.set_title('Inset Plot')

ax.legend(loc = 4)

axins.legend()

Fig 12

The main plot here has the default grid, which can be created by simply calling the grid() function.

The grid lines too can be modified just like the plot lines. These modifications can be seen in the inset plot. The grid lines in it have a different colour, style and width compared to the ones in the main plot.