Python | Object Oriented Style Plotting in Matplotlib

In this tutorial, we are going to learn how to plot figures using an object-oriented style in matplotlib?
Submitted by Anuj Singh, on August 17, 2020

There are two ways to do plotting in Matplotlib,

  • Creating axes and figures explicitly by initializing objects for a figure. We can call methods on them and therefore it is called as object-oriented (OO) style.
  • Pyplot automatically creates and manages the figures and axes. We can use matplotlib.pyplot inbuilt defined functions for plotting and pyplot api itself calculates to operate on figures.

Illustrations:

Object Oriented Style Plotting in Matplotlib (1)

Object Oriented Style Plotting in Matplotlib (2)

Python for code object-oriented style plotting in matplotlib

import numpy as np
import matplotlib.pyplot as plt

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

fig, ax = plt.subplots()  
ax.plot(x, x, label='linear')  
ax.plot(x, x**2, label='quadratic')  
ax.step(x, x**3, label='cubic steps')  
ax.set_xlabel('x label')  
ax.set_ylabel('y label')  
ax.set_title("A simple plot using Object Oriented Style")  
ax.legend()  
ax.grid()

plt.figure()
plt.plot(x, x, label='linear')  
plt.plot(x, x**2, label='quadratic')  
plt.step(x, x**3, label='cubic steps')  
plt.xlabel('x label')  
plt.ylabel('y label')  
plt.title("A simple plot using automatically created by pyplot")  
plt.legend()  
plt.grid()

Output:

Output is as Figure


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.