Home »
Python »
Python Data Visualization
Python | Vertical Subplot
Python | Vertical Subplot: In this article, we are going to learn about the vertical subplot and its Python implementation.
Submitted by Anuj Singh, on July 15, 2020
Many times while plotting a figure, we have to compare different functions simultaneously. Then we do have the option to plot in a single figure but this is helpful only for a limited number of functions. If there are a greater number of functions, then plotting in the same figure turns out to be messy. Therefore, matplotlib provides a feature of subploting in which we can plot more than one plot in one figure with more than one graph. This is one of the most often used tools for best data visualization and the figure shows an example.
Syntax:
#plotting in a one figure
plt.figure()
#upper part of subplot
plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'yo')
plt.title('SubPlot Example')
#lower part of subplot
plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'go')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
Note: Both the graphs are independent, as the following figure(1) adds grid to one graph and the other remains the same and furthermore in figure(2), both have grid.
Python code for vertical subplot
# Data Visualization using Python
# Vertical Subplot
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
plt.figure()
plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'yo')
plt.title('SubPlot Example')
plt.ylabel('Damped oscillation')
plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'go')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
#Applying grid to one
plt.figure()
plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'yo')
plt.title('Figure 1')
plt.ylabel('Damped oscillation')
plt.grid()
plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'go')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
#Applying grid to both
plt.figure()
plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'yo')
plt.title('Figure 2')
plt.ylabel('Damped oscillation')
plt.grid()
plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'go')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.grid()
plt.show()
Output:
Output is as figure