Tags: , , , , , , ,



In this tutorial, we will see basic syntax of producing plots for data visualization using the matplotlib module. matplotlib and seaborn are widely used for basic data visualization. seaborn actually uses the underlying functionalities of the matplotlib module for more beautiful less code-oriented visualizations.

Let’s first import the module like this

import matplotlib.pyplot as plt

If you are using the Jupyter Notebook, also add the following:

# Only for jupyter notebook
%matplotlib inline


Basic Plotting

The simplest way of plotting $(x,y)$-values is to use matplotlib.pyplot.plot(x,y). I have added the labels and titles here as well.

x = [1,2,3,4,5]
y = [1,4,9,16,25]

plt.plot(x, y, 'black')
plt.xlabel('Write your X-label')
plt.ylabel('Write your Y-label')
plt.title('Write your plot title')

Basic Subplotting

The most basic subplotting can be visualized using the subplot allocation and numbering. $(1,2,1)$ means the subplot has allocation for one row (first value) and two columns (second value) (that means two subplots possible) where the last value defines the first column.

x = [1,2,3,4,5]
y1 = [1,4,9,16,25]
y2 = [1,8,27,64,125]

plt.plot(x, y1, 'r+-')
plt.plot(x, y2, 'g*-');

Similarly, if you want to have three subplots in one row:

x = [1,2,3,4,5]
y1 = [1,4,9,16,25]
y2 = [1,8,27,64,125]
y3 = [2,4,6,8,10]

plt.plot(x, y1, 'ro-')
plt.plot(x, y2, 'g*-')
plt.plot(x, y3, 'b+-');

Plotting using plt.figure() class

Basic Plotting

You can create a basic plot object by using the matplotlib.pyplot.figure() class.

fig = plt.figure()

# define axes in this format:
# [x0, y0, width, height] (range 0 to 1)
axes = fig.add_axes([0, 0, 1, 1]) 

# Plot on that set of axes
axes.plot(x, y, 'ro-')
axes.set_xlabel('Set X-label')
axes.set_ylabel('Set y-label')
axes.set_title('Write your title');

Inset Plotting

You can generate an inset plot by defining the axes value for the second plot.

fig = plt.figure()

axes1 = fig.add_axes([0, 0, 1, 1]) # larger axes
axes2 = fig.add_axes([0.65, 0.25, 0.25, 0.2]) # inset axes

axes1.plot(x, y1, 'b*-')
axes1.set_xlabel('X label')
axes1.set_ylabel('Y label')
axes1.set_title('Axes 1 Title')

axes2.plot(x, y2, 'r+-')
axes2.set_xlabel('X label')
axes2.set_ylabel('Y label')
axes2.set_title('Axes 2 Title');

Automatic Subplots

The matplotlib.pyplot.subplots() object can assign automatic subplots.

# Automatic fig and axes
fig, axes = plt.subplots()

axes.plot(x, y, 'r')
axes.set_xlabel('X label')
axes.set_ylabel('Y label')

You can define the number of rows and columns under nrows and ncols parameters while creating objects.

fig, axes = plt.subplots(nrows=1, ncols=3)
yList = [y1,y4,y5]
for roy,j in zip(axes,yList):
    roy.plot(x, j, 'b')
    roy.set_xlabel('X label')
    roy.set_ylabel('Y label')

Other Customizations

Custom Figure Size

You can define custom figure size using the figsize parameter. The length and height values are defined inside a tuple.

fig, axes = plt.subplots(figsize=(15,5))

axes.plot(x, y, 'g')
axes.set_xlabel('X label')
axes.set_ylabel('Y label')


Save a Figure

Save a figure using the <fig_obj>.savefig() method

fig.savefig("thisistest.png", dpi=300)

Multiple Plots in one figure

In the following example, multiple plots has been be drawn using <axes_obj>.plot() method multiple times.

fig = plt.figure()
axes = fig.add_axes([0,0,1,1])

axes.plot(x, y1)
axes.plot(x, y2)


Use <axes_obj>.set_title() method to set the title of the plot

fig = plt.figure()
axes = fig.add_axes([0,0,1,1])

axes.plot(x, y1)
axes.plot(x, y2)

ax.set_title("write your title")


The legend is defined by providing a name to the label option.

fig = plt.figure()
axes = fig.add_axes([0,0,1,1])

axes.plot(x, y1, label="sin(x)")
axes.plot(x, y2, label="cos(x)")

Legend locations can be set like this

ax.legend(loc=0) # optimal location
ax.legend(loc=1) # upper right corner
ax.legend(loc=2) # upper left corner
ax.legend(loc=3) # lower left corner
ax.legend(loc=4) # lower right corner

More customization is possible using the bbox_to_anchor option. For example, to put the legend-box outside right top, you can use the following code:

plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

Axis Labels

Use <axes_obj>.set_xlabel() and <axes_obj>.set_ylabel() to set axis labels in $x$ and $y$ directions, respectively.

fig = plt.figure()
axes = fig.add_axes([0,0,1,1])

axes.plot(x, y1)
axes.plot(x, y2)


fig, ax = plt.subplots()
axes.plot(x, y1, 'b.-') # blue dotted line
axes.plot(x, y2, 'g--') # green dashed line

Also, color parameter is available to set custom color hex codes

axes.plot(x, y1, color="#7a7a7a")
axes.plot(x, y2, color="#FFC98A") 

Line Width

Line width can be set using the lw parameter.

fig, ax = plt.subplots()
axes.plot(x, y1, lw=3,'b.-')
axes.plot(x, y2, lw=3,'g--')

Line Style

Use ls parameter to define a custom line style

fig, ax = plt.subplots()
axes.plot(x, y1,ls='-')
axes.plot(x, y2,ls='--')

Custom Marker

Use custom marker using the marker parameter.

fig, ax = plt.subplots()
axes.plot(x, y1, color="blue", lw=3, ls='-', marker='+')
axes.plot(x, y2, color="blue", lw=3, ls='--', marker='o')


Use logarithmic scales for large difference values

fig, axes = plt.subplots(1, 2, figsize=(10,4))
axes[0].plot(x, x**3, x, np.exp(x))
axes[0].set_title("Regular scale")

axes[1].plot(x, x**3, x, np.exp(x))
axes[1].set_title("Logarithmic scale (y)");


You can use styles for different looking plots. Simply check the available styles using the following command


You can find the styles names as follows:

['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']

Now, check all styles using a loop:

import math

n = len(plt.style.available)
num_rows = math.ceil(n/4)

fig = plt.figure(figsize=(15, 15))

for i, s in enumerate(plt.style.available):
    with plt.style.context(s):
        ax = fig.add_subplot(num_rows, 4, i+1)
        for i in range(1, 4):
            ax.plot(x, i * x**2, label='Group %d' % i)
            ax.set_xlabel(s, color='black')

In this post, I tried to cover basic plotting using the matplotlib module. So far, we have learnt how to draw line charts. In the next tutorial, we will learn other plots, for example, bar plots, pie plots, scatter plots, and others.

For accessing all data science in python related posts, check this post:

Collection of Data Science in Python Posts in my Blog.

Thanks for your patience. Have a good day!

Leave a Comment