Skip to main content

Creating plots using Functional way(using `plt.plot()` or `plt.subplot()`)

· 12 min read
Shaurya Singhal

Source: View original notebook on GitHub

Category: Machine Learning / Learn ML libraries

<img src = 'images/python_matplotlib.jpg'>

Introduction

Matplotlib is the library of data visualization with Python. It was created by John Hunter. He created it to try to replicate MatLab's (another programming language) plotting capabilities in Python.

It is an excellent 2D and 3D graphics library for generating scientific figures.

Some of the major Pros of Matplotlib are:

  • Generally easy to get started for simple plots
  • Support for custom labels and texts
  • Great control of every element in a figure
  • High-quality output in many formats
  • Very customizable in general

Matplotlib web page: http://matplotlib.org/

Installation

pip install matplotlib

Importing

Import the matplotlib.pyplot module under the name plt (the tidy way):

import matplotlib.pyplot as plt

use: plt.show() at the end of all your plotting commands to have the figure pop up in another window.

import numpy as np
x = np.linspace(0, 5, 11)
y = x ** 2
x

Output:

array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ])
y

Output:

array([ 0.  ,  0.25,  1.  ,  2.25,  4.  ,  6.25,  9.  , 12.25, 16.  ,
20.25, 25. ])

Basic Matplotlib Functions

  • plt.plot()
  • plt.xlabel()
  • plt.ylabel()
  • plt.title()
  • plt.legend()
  • plt.subplot()
  • plt.figure() # to get empty canvas
  • plt.bar(), plt.barh()
  • plt.pie()
  • plt.hist()

Creating plots using Functional way(using plt.plot() or plt.subplot())

plt.plot(x, y, 'r') # 'r' is the color red
plt.xlabel('X Axis ')
plt.ylabel('Y Axis ')
plt.title('Graph of x- square')
plt.show()

Output

Creating Multiplots on Same Canvas

# plt.subplot(nrows, ncols, plot_number)

# ==> creates a canvas of nrows and ncols here 2,2 ; for each subplot just give plot_number to identify the cell.
plt.subplot(2,2,1)
plt.plot(x, y, 'r--') # More on color options later
plt.subplot(2,2,2)
plt.plot(y, x, 'g*-');
plt.subplot(2,2,3)
plt.plot(x, y, 'b^-') # More on color options later
# plt.subplot(2,2,4)
# plt.plot(y, x, 'g*-');

Output

Output:

[&lt;matplotlib.lines.Line2D at 0xfc7bc50&gt;]

Matplotlib Object Oriented Method

  • Introduction of Matplotlib's Object Oriented API : This means we will instantiate figure objects and then call methods or attributes from that object.

  • give way more control over graph plotting then functional way

  • create figure objects using plt.figure().

  • and then just call methods or attributes off of that object.

    - plt.figure().add_axes()
- plt.figure().plot()
- plt.figure().set_xlabel()
- plt.figure().set_ylabel()
- plt.figure().set_title()

  • creating various plots on same canvas using Object-Oriented way

    • plt.subplots() # see the 's' here in subplot's'.
  • This approach is nicer when dealing with a canvas that has multiple plots on it.

To begin we create a figure instance. Then we can add axes to that figure:

# Create Figure (empty canvas)
fig = plt.figure()

# Add set of axes to figure
axes = fig.add_axes([0, 0, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)

# Plot on that set of axes
axes.plot(x, y, 'b')
axes.set_xlabel('Set X Label') # Notice the use of set_ to begin methods
axes.set_ylabel('Set y Label')
axes.set_title('Set Title')

fig.show()

Output

Output:

c:\users\shaurya singhal\appdata\local\programs\python\python37-32\lib\site-packages\matplotlib\figure.py:445: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.
% get_backend())

Code is a little more complicated, but the advantage is that we now have full control of where the plot axes are placed, and we can easily add more than one axis to the figure:

# Creates blank canvas
fig = plt.figure()

axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes

# Larger Figure Axes 1
axes1.plot(x, y, 'b')
axes1.set_xlabel('X_label_axes1')
axes1.set_ylabel('Y_label_axes1')
axes1.set_title('Axes 1 Title')

# Insert Figure Axes 2
axes2.plot(y, x, 'r')
axes2.set_xlabel('X_label_axes2')
axes2.set_ylabel('Y_label_axes2')
axes2.set_title('Axes 2 Title');

Output

subplots()

The plt.subplots() object will act as a more automatic axis manager.

Basic use cases:

# Use similar to plt.figure() except use tuple unpacking to grab fig and axes
# plt.subplots(nrows,ncols) # no subplot number
fig, axes = plt.subplots() # creates a figure and set of subplots

# Now use the axes object to add stuff to plot
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');

Output

# Then you can specify the number of rows and columns when creating the subplots() object:
import matplotlib.pyplot as plt
fig,axes = plt.subplots(5,5)

Output

fig

Output

axes

Output:

array([[&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FDBC930&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FDD2A10&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FDEB930&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FE069D0&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FE2A050&gt;],
[&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FE44130&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FE5E290&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FE7A370&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FE8EE50&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FEA9F30&gt;],
[&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FECC630&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FEE9710&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FF047F0&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FF1E8D0&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FF3A9B0&gt;],
[&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FF55A90&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FF70B70&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FF8BC50&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FFA6D30&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FFC1E10&gt;],
[&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FFDBEF0&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x0FFF4FD0&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x1001B0D0&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x100351B0&gt;,
&lt;matplotlib.axes._subplots.AxesSubplot object at 0x1004F290&gt;]],
dtype=object)

We can iterate through this array:

import numpy as np
x= np.arange(10)
for axis in axes:
for ax in axis:
ax.plot(x, x**2, 'b')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title')

plt.tight_layout()
# Display the figure object
fig

Output

Output:

&lt;Figure size 432x288 with 0 Axes&gt;

A common issue with matplolib is overlapping subplots or figures. We ca use fig.tight_layout() or plt.tight_layout() method, which automatically adjusts the positions of the axes on the figure canvas so that there is no overlapping content:

fig, axes = plt.subplots(nrows=1, ncols=2)

for ax in axes:
ax.plot(x, x*2, 'g')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title')

fig
plt.tight_layout()

Output

Figure size, aspect ratio and DPI

Matplotlib allows the aspect ratio, DPI and figure size to be specified when the Figure object is created. You can use the figsize and dpi keyword arguments.

  • figsize is a tuple of the width and height of the figure in inches
  • dpi is the dots-per-inch (pixel per inch).

For example:

fig = plt.figure(figsize=(8,3), dpi=100)
axes = fig.add_axes((0.2,.2,.8,.8))
axes.plot(x,x**3)

Output

Output:

[&lt;matplotlib.lines.Line2D at 0x126d8870&gt;]

The same arguments can also be passed to layout managers, such as the subplots function:

fig, axes = plt.subplots(figsize=(12,3))
x= np.arange(10)+1 # to avoid Zero
axes.plot(x, 1/x, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');

Output

Saving figures

Matplotlib can generate high-quality output in a number formats, including PNG, JPG, EPS, SVG, PGF and PDF.

To save a figure to a file we can use the savefig method in the Figure class:

fig.savefig("filename.png")

Here we can also optionally specify the DPI and choose between different output formats:

fig.savefig("filename.png", dpi=200)
fig.savefig('pdffile.pdf')
fig.savefig('svgfile.svg')

Graph Decoration

1. Legends, labels and titles

Now that we have covered the basics of how to create a figure canvas and add axes instances to the canvas, let's look at how decorate a figure with titles, axis labels, and legends.

Figure titles

A title can be added to each axis instance in a figure. To set the title, use the set_title method in the axes instance:

ax.set_title("title");

Axis labels

Similarly, with the methods set_xlabel and set_ylabel, we can set the labels of the X and Y axes:

ax.set_xlabel("x")
ax.set_ylabel("y");

Legends

You can use the label="label text" keyword argument when plots or other objects are added to the figure, and then using the legend method without arguments to add the legend to the figure:

fig = plt.figure()

ax = fig.add_axes([0,0,1,1])

ax.plot(x, x**2, label="x**2")
ax.plot(x, x**3, label="x**3")
ax.legend(loc=0, fontsize =50) # takes various methods but loc and fontsize are our main concern

Output

Output:

&lt;matplotlib.legend.Legend at 0x111b08b0&gt;

see the docs at https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html

2. Setting colors, linewidths, linetypes

Matplotlib gives you a lot of options for customizing colors, linewidths, and linetypes.

With matplotlib, we can define the colors of lines and other graphical elements in a number of ways. First of all, we can use the MATLAB-like syntax where 'b' means blue, 'g' means green, etc. The MATLAB API for selecting line styles are also supported: where, for example, 'b.-' means a blue line with dots:

# MATLAB style line color and style 
fig, ax = plt.subplots()
ax.plot(x, x**2, 'b.-') # blue line with dots
ax.plot(x, x**3, 'g--') # green dashed line

Output

Output:

[&lt;matplotlib.lines.Line2D at 0x1293ca70&gt;]

3. Colors with the color= parameter

We can also define colors by their names or RGB hex codes and optionally provide an alpha value using the color and alpha keyword arguments. Alpha indicates opacity.

fig, ax = plt.subplots()
ax.plot(x,x,color='blue')
ax.plot(x, x+1, color="blue", alpha=0.2) # 20%-transparant
ax.plot(x, x+2, color="#8B008B") # RGB hex code
ax.plot(x, x+3, color="#FF8C00") # RGB hex code

Output

Output:

[&lt;matplotlib.lines.Line2D at 0x14f11b0&gt;]

4. Line and marker styles

To change the line width, we can use the linewidth or lw keyword argument. The line style can be selected using the linestyle or ls keyword arguments:

fig, ax = plt.subplots(figsize=(12,6),dpi=150)

# showing line- width options
ax.plot(x, x+1, color="red", linewidth=0.25)
ax.plot(x, x+2, color="red", linewidth=0.50)
ax.plot(x, x+3, color="red", linewidth=1.00)
ax.plot(x, x+4, color="red", linewidth=2.00)

# possible linestype options ‘-‘, ‘-.’, ‘:’, ‘steps’
ax.plot(x, x+5, color="green", lw=3, linestyle='-')
ax.plot(x, x+6, color="green", lw=3, ls='-.')
ax.plot(x, x+7, color="green", lw=3, ls=':')

# custom dash
line, = ax.plot(x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...

# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ...
ax.plot(x, x+ 9, color="blue", lw=3, ls='-', marker='+')
ax.plot(x, x+10, color="blue", lw=3, ls='--', marker='o')
ax.plot(x, x+11, color="blue", lw=3, ls='-', marker='s')
ax.plot(x, x+12, color="blue", lw=3, ls='--', marker='1')

# marker size and color
ax.plot(x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2)
ax.plot(x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4)
ax.plot(x, x+15, color="purple", lw=1, ls='-', marker='o', markersize=8, markerfacecolor="red")
ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8,
markerfacecolor="yellow", markeredgewidth=3, markeredgecolor="green");

Output

Control over axis appearance

In this section we will look at controlling axis sizing properties in a matplotlib figure.

Plot range

We can configure the ranges of the axes using the set_ylim and set_xlim methods in the axis object, or axis('tight') for automatically getting "tightly fitted" axes ranges:

fig, axes = plt.subplots(1, 3, figsize=(12, 4))

axes[0].plot(x, x**2, x, x**3) # can take various (x,y pairs) for more lines
axes[0].set_title("default axes ranges")

axes[1].plot(x, x**2, x, x**3)
axes[1].axis('tight')
axes[1].set_title("tight axes")

axes[2].plot(x, x**2, x, x**3)
axes[2].set_ylim([0, 60])
axes[2].set_xlim([2, 5])
axes[2].set_title("custom axes range");

Output

Special Plot Types

There are many specialized plots we can create, such as barplots, histograms, scatter plots, and much more.

x=np.arange(10)
plt.scatter(x,x**2)

Output

Output:

&lt;matplotlib.collections.PathCollection at 0x1853e970&gt;
from random import sample
data = sample(range(1, 1000), 10)
print(data)
print(type(data))
# plt.hist(data)

Output:

[289, 935, 574, 996, 252, 962, 640, 113, 39, 347]
&lt;class 'list'&gt;
plt.hist(data,bins=5,color='blue',rwidth=.5)

Output

Output:

(array([2., 3., 1., 1., 3.]),
array([ 39. , 230.4, 421.8, 613.2, 804.6, 996. ]),
&lt;a list of 5 Patch objects&gt;)

Further reading

Other 2D plot styles

In addition to the regular plot method, there are a number of other functions for generating different kind of plots. See the matplotlib plot gallery for a complete list of available plot types: http://matplotlib.org/gallery.html. Some of the more useful ones are show below:

import numpy as np
import matplotlib.pyplot as plt
n = np.array([0,1,2,3,4,5])
x = np.array([1,2,3,4,5])
fig, axes = plt.subplots(1, 4, figsize=(12,3))

axes[0].scatter(x, x + 0.25*np.random.randn(len(x)))
axes[0].set_title("scatter")

axes[1].step(n, n**2, lw=2)
axes[1].set_title("step")

axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
axes[2].set_title("bar")

axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);
axes[3].set_title("fill_between");

Output

Text annotation

Annotating text in matplotlib figures can be done using the text function.

import numpy as np
x = np.arange(10)
fig, ax = plt.subplots()

ax.plot(x, x**2, x, x**3)

ax.text(6,70, r"$y=x^2$", fontsize=20, color="blue")
ax.text(4,200, r"$y=x^3$", fontsize=20, color="green");

Output

3D figures

To use 3D graphics in matplotlib, we first need to create an instance of the Axes3D class. 3D axes can be added to a matplotlib figure canvas in exactly the same way as 2D axes; or, more conveniently, by passing a projection='3d' keyword argument to the add_axes or add_subplot methods.

alpha = 0.7
phi_ext = 2 * np.pi * 0.5

def flux_qubit_potential(phi_m, phi_p):
return 2 + alpha - 2 * np.cos(phi_p) * np.cos(phi_m) - alpha * np.cos(phi_ext - 2*phi_p)
phi_m = np.linspace(0, 2*np.pi, 100)
phi_p = np.linspace(0, 2*np.pi, 100)
X,Y = np.meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T
import matplotlib
from mpl_toolkits.mplot3d.axes3d import Axes3D

Surface plots

fig = plt.figure(figsize=(14,6))

# `ax` is a 3D-aware axis instance because of the projection='3d' keyword argument to add_subplot
ax = fig.add_subplot(1, 2, 1, projection='3d')

p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)

# surface_plot with color grading and color bar
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=matplotlib.cm.coolwarm, linewidth=0, antialiased=False)
cb = fig.colorbar(p, shrink=0.5)

Output

Wire-frame plot

fig = plt.figure(figsize=(8,6))

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

p = ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4)

Output

Coutour plots with projections

fig = plt.figure(figsize=(8,6))

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

ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
cset = ax.contour(X, Y, Z, zdir='z', offset=-np.pi, cmap=matplotlib.cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-np.pi, cmap=matplotlib.cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=3*np.pi, cmap=matplotlib.cm.coolwarm)

ax.set_xlim3d(-np.pi, 2*np.pi);
ax.set_ylim3d(0, 3*np.pi);
ax.set_zlim3d(-np.pi, 2*np.pi);

Output