Multiple plots with same x axis in Matplotlib Python

In this tutorial, you will learn how to create multiple plots with the same X-axis using Python. At times, when you have a single parameter (independent variable) and many dependent variables, so you want to plot those on the same x-axis ( independent variable) for easy visualization.

Multiple plots

Let’s create the plot for three trigonometric functions – sinx, cosx, and tanx. For creating multiple plots, we use the plt.subplot() function which takes the parameter asking for rows and columns. In other words, it will ask how many plots will be in rows and columns. For e.g., In our case, we will have 3 rows and 1 column only. We will generate an array containing values of these trigonometric functions using the numpy library.
plt.tight_layout()is used to prevent the overlap of the subplots.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)  # assuming x values are in radians
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# Converting radians to degrees for x-axis 
x_degrees = np.degrees(x)


fig, axs = plt.subplots(3, 1, figsize=(8, 6))


axs[0].plot(x_degrees, y1, color='blue')
axs[0].set_title('Sin(x)')
axs[0].set_ylabel('Amplitude')

axs[1].plot(x_degrees, y2, color='red')
axs[1].set_title('Cos(x)')
axs[1].set_ylabel('Amplitude')

axs[2].plot(x_degrees, y3, color='green')
axs[2].set_title('Tan(x)')
axs[2].set_ylabel('Amplitude')
axs[2].set_xlabel('Degrees')  

plt.tight_layout()  
plt.show()

Superimposing in a single plot

Sometimes, you need to plot values in a single plot as it is easy to conclude. In that case, we just simply plot all the curves in a single plot. The important thing to note here is you have to adjust the values on the Y-axis as the range varies with different curves. The tanx function goes to infinity, whereas the sinx and cosx range is limited to -1 to 1 only. We limit the values of the Y-axis using the plt.ylim() function. Also, this time, I am allowing grids in the plot as they made work easy in verification. However, it is a personal choice.
Furthermore, I have done some formatting in the X-axis labels part. As you can see in the above output, degrees are divided in the step range of 50. I want to reduce it to 30 degrees for our better understanding. Apart from that, when you convert the radians into degrees, there might be chances that they become float data type, so to avoid that, we are converting them back to integer data type. For this formatting, I am using the plt.gca() function.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as ticker

x = np.linspace(0, 2*np.pi, 100)  # assuming x values are in radians
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# Converting radians to degrees for x-axis 
x_degrees = np.degrees(x)


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

plt.plot(x_degrees, y1, label='Sin(x)', color='blue')
plt.plot(x_degrees, y2, label='Cos(x)', color='red')
plt.plot(x_degrees, y3, label='Tan(x)', color='green')

plt.title('Trigonometric Functions')
plt.xlabel('Degrees')
plt.ylabel('Amplitude')
plt.legend()

plt.grid(True)

# Limiting the range of Y-axis for easy visualisation
plt.ylim(-5, 5)

# Formatting labels on X-axis
plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(30))  
plt.gca().xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))  # display as integer

plt.show()

Leave a Reply

Your email address will not be published. Required fields are marked *