Saturday, December 30, 2017

Matplotlib/subplot/python Syntax and Analysis “fig, ax = plt.subplots()”


The Matplotlib subplot() function can be called to plot two or more plots in one figure. Matplotlib supports all kind of subplots including 2×1 vertical, 2×1 horizontal or a 2×2 grid.


# Import required library
import matplotlib.pyplot as plt
import numpy as np

#First create some toy data:
x = np.linspace(0, 5, 11)
y = x ** 2

#Instantiate figure and axes object. 
# bydefualt on not passing any parameters in constructor, Just a figure and one subplot
fig, ax = plt.subplots()
#Set Data
ax.plot(x, y)
#Set Title for the graph
ax.set_title('Simple plot')


Analysis of used code

#Instantiate figure and axes object. 
fig, ax = plt.subplots()

Important feature of the below code is we are using 2 variables for assignment on instantiation of object.

Reasoning

plt.subplots() is a function that returns a tuple containing a figure and axes object(s). Thus when using fig, ax = plt.subplots() you unpack this tuple into the variables fig and ax.Thus this can also be read as 2 below statement combined as one.

fig = plt.figure()
ax = fig.add_subplot(111)



f : matplotlib.figure.Figure object

ax : Axes object or array of Axes objects.

ax can be either a single  matplotlib.axes.Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above.

No comments: