MPL - OO (Explicit) Style vs. pyplot

PHOTO EMBED

Sat Sep 24 2022 06:11:47 GMT+0000 (Coordinated Universal Time)

Saved by @sfull

# OO (Explicit) Style
# Explicitly create Figures and Axes, and call methods on them

# EXPLICIT: Uses fig, ax = plt.subplots() --> ax.plot() --> ax.set_xlabel('x')...
# IMPLICIT: Uses plt.figure() --> plt.plot()  --> plt.xlabel('x')...
# i.e. IMPLICIT uses plt.___() to reference 

x = np.linspace(start=0, stop=2, num=100)

# Note that even in the OO-style, we use `.pyplot.figure` to create the Figure.
fig, ax = plt.subplots(figsize=(15, 8))

# ax is an Axes (plot) object
ax.plot(x=x, y=x, label='linear')
ax.plot(x=x, y=x**2, label='quadratic')
ax.plot(x=x, y=x**3, label='cubic')

# These methods set Axes.Axis objs (literal x- & y-axis lines)
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_title("Simple Plot")
ax.legend();  

#-------------------------------------------------------------#

# "pyplot-style" (vs Explicit)
# Implicitly create and manage the Figures and Axes, and use pyplot functions for plotting.

# EXPLICIT: Uses fig, axe s= plt.subplots() --> ax.plot() --> ax.set_xlabel('x')...
# IMPLICIT: Uses plt.figure() --> plt.plot()  --> plt.xlabel('x')...

x = np.linspace(0, 2, 100)

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

plt.plot(x, x, label='linear')  # Creates axes
plt.plot(x, x**2, label='quadratic')  # Add new line to existing axes
plt.plot(x, x**3, label='cubic')

plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend();
content_copyCOPY