Question:
How to allign two plots in Matplotlib?

Solution


You can use ‘subplots()’ function to create various subplots within the aligned two plots in Metroplotlib. Once you specify the ‘subplot’ configuration, you can easily control the alignment of the plots. Here is the demonstration illustrating the process of aligning two plots horizontally. 


import matplotlib.pyplot as plt

import numpy as np


# Generate some data for plotting

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

y1 = np.sin(x)

y2 = np.cos(x)


# Create a figure and two subplots side by side

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))


# Plot data on the first subplot (ax1)

ax1.plot(x, y1, color='blue')

ax1.set_title('Sin Wave')


# Plot data on the second subplot (ax2)

ax2.plot(x, y2, color='red')

ax2.set_title('Cosine Wave')


# Adjust layout to prevent overlap

plt.tight_layout()


# Show the plots

plt.show()


In the above example, we can create a figure with one row and two columns of subplots using ‘plt.subplots(1, 2)’ and aligning these columns horizontally. The ax1 and ax2 variables represent the axes of the first and second subplots, respectively. Then, you can plot your data on each subplot using the corresponding axes (ax1.plot() and ax2.plot()). Finally, plt.tight_layout() adjusts the layout to prevent overlapping elements. 


Suggested blogs:

>>What is microservice architecture, and why is it better than monolithic architecture?

>>What is pipe in Angular?

>>What makes Python 'flow' with HTML nicely as compared to PHP?

>>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?


Submit
0 Answers