Open In App

Draw Multiple Y-Axis Scales In Matplotlib

Why areMatplotlib is a powerful Python library, with the help of which we can draw bar graphs, charts, plots, scales, and more. In this article, we’ll try to draw multiple Y-axis scales in Matplotlib.

Why are multiple Y-axis scales important?

Multiple Y-axis scales are necessary when plotting datasets with different units or measurement scales, aiding in clear comparison without distortion. This is necessary when:



  1. Different Units or Measurement Scales:
    • If you have multiple datasets with different units or measurement scales, using separate Y-axes can prevent distortion and make it easier to compare trends.
  2. Correlated but Differently Scaled Data:
    • When you have datasets that are correlated but have different magnitudes, multiple Y-axes can help visualize their patterns without one dataset dominating the plot.
  3. Combining Disparate Data:
    • If you need to overlay two or more datasets with disparate data types (e.g., temperature and rainfall), multiple Y-axes allow you to represent each variable with its own scale.
  4. Highlighting Relationships:
    • Multiple Y-axes can be useful for highlighting relationships or correlations between two datasets that may have different ranges or units.
  5. Avoiding Clutter:
    • When you have many datasets to display, using multiple Y-axes can prevent clutter and make the plot more readable.
  6. Enhancing Interpretation:
    • In some cases, having multiple Y-axes can enhance the interpretability of the plot by providing a clear visual separation between different datasets.

Importing necessary articles

import matplotlib.pyplot as plt
import numpy as np




Here we also need to import NumPy, as we’ll be needing that later.

Creating Sample data

Here, we will be using NumPy for this part.






x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.exp(-x)
y3 = 100 * np.cos(x)

We’re going to create our first Y-axis. To create an axis, we use Matplotlib.

1. Creating the First Y-Axis

let’s create our first Y-Axis:




fig, ax1 = plt.subplots()

Output:

Here, we’ve created a matplotlib figure and axis “ax1” to represent the first y-axis. “plt.subplots(” basically used to create single subplot and also figures.

2. Plotting the First Dataset on the First Y-Axis

Now our next step is to plot the first data set on the first Y-Axis. Here, we plot the first dataset that is “y1” we defined and plot on the first Y-Axis “ax1” with the help of “ax1.plot()”. Here we used “b” as the color, as we want it to be blue and then we set the lables of X and Y axes. Also we’ve used “tick_params()” to set the color of Y-Axis to blue.




# Create the first plot with the left Y-axis
fig, ax1 = plt.subplots(figsize=(8, 6))
# Plot the first dataset on the first Y-axis
ax1.plot(x, y1, 'b', label='y1 (sin(x))'# Shorthand 'b' for blue color
 
# Set labels and ticks for the first Y-axis
ax1.set_xlabel('X-axis')
ax1.set_ylabel('y1', color='b')
ax1.tick_params('y', colors='b')
 
# Display the plot
plt.title('Plotting the First Dataset on the First Y-Axis')
plt.show()

Output:

Our first Y-Axis is successfully created, now we’ll create a second Y-Axis that will share the same X-Axis. We use trinx() function to get the desired result.

3. Creating a Second Y-Axis




ax2 = ax1.twinx()

Here, we’re creating a second axis “ax2″ that will share the same X-Axis with the first Y-Axis using “ax1.twin()” method.

4. Plotting the Second Dataset on the Second Y-Axis

Here, we are plotting a second dataset on the second y-axis we’ve created above. Now we’re using “g” as we want to set the color to green. Then it sets the labels for the y-axis. By using “tick_params()” we can set the color of Y-Axis to blue. Now we will plot the second data set on the second Y-Axis.




fig, ax2 = plt.subplots(figsize=(8, 6))
ax2.plot(x, y2, 'g', label='y2 (exp(-x))')
ax2.set_ylabel('y2', color='g')
ax2.tick_params('y', colors='g')
# Display the plot
plt.title('Plotting the Second Dataset on the Second Y-Axis')
plt.show()

Output:

Let’s then create a third Y-Axis that will share the same X-Axis that shared before.

5. Creating a Third Y-Axis




ax3 = ax1.twinx()

Our next step is to plot the third data set on the third Y-Axis.

6. Plotting the Third Dataset on the Third Y-Axis

Here, we are plotting a second dataset on the second y-axis we’ve created above. Now we’re using “g” as we want to set the color to green. Then it sets the labels for the y-axis. By using “tick_params()” we can set the color of Y-Axis to blue.




fig, ax3 = plt.subplots(figsize=(8, 6))
ax3.plot(x, y3, 'r', label='y3 (100*cos(x))')
ax3.set_ylabel('y3', color='r')
ax3.tick_params('y', colors='r')
# Display the plot
plt.title('Plotting the third Dataset on the third Y-Axis')
plt.show()

Output:

7. Adding Legends

Here comes our legendary part. We’ll now add the legends by using the “legend()” and get_legend_handles_lablels()” functions.




lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
lines3, labels3 = ax3.get_legend_handles_labels()
lines = lines1 + lines2 + lines3
labels = labels1 + labels2 + labels3

8. Title and Displaying the Plot

And we’re all done. Now our last step is to title and then show the plot that will create the multiple Y-Axis Scales and show us the plot, amalgamating all the plots above.




plt.title('Multiple Y-axis Scales')
plt.show()

And we’re done. We’ve discussed from starting to the end on how to create and show mutiple Y-Axis Scales with the help of matplotlib. Let’s now see how our whole project looks like. Finally,. we title and display out plot using “plt.title()” and “plt.show()”. It’ll show us our complete plot with the multiple y-axis scales as we have seen in the result above. In short this creates a single plot with the three y-axes with a single x-axis. We’ve made it easy to visualize and compare multiple datasets with different scales on a single plot.




import matplotlib.pyplot as plt
import numpy as np
 
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.exp(-x)
y3 = 100 * np.cos(x)
 
fig, ax1 = plt.subplots()
 
ax1.plot(x, y1, 'b', label='y1 (sin(x)')
ax1.set_xlabel('X-axis')
ax1.set_ylabel('y1', color='b')
ax1.tick_params('y', colors='b')
 
ax2 = ax1.twinx()
 
ax2.plot(x, y2, 'g', label='y2 (exp(-x))')
ax2.set_ylabel('y2', color='g')
ax2.tick_params('y', colors='g')
 
ax3 = ax1.twinx()
 
ax3.plot(x, y3, 'r', label='y3 (100*cos(x))')
ax3.spines['right'].set_position(('outward', 60))
ax3.set_ylabel('y3', color='r')
ax3.tick_params('y', colors='r')
 
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
lines3, labels3 = ax3.get_legend_handles_labels()
lines = lines1 + lines2 + lines3
labels = labels1 + labels2 + labels3
plt.legend(lines, labels, loc='upper right')
 
plt.title('Multiple Y-axis Scales')
plt.show()

Output:

In this image, we can clearly see the three y-axes and x-axis and understand how well our plot has been drawn.

Conclusion

We’ve discussed on how to import the required libraries i.e. matplotlib and numpy in this project, then we created sample data for multiple data sets, we then discussed about first y-axis, second y-axis, third y-axis and in between we took help of the “twinx()” function to create the y-axes that shares the same x-axis. Then after adding legends we finally plotted our scales and successfully drawn the scales. Hope this was helpful in craeting multiple Y-Axis Scales in Matplotlib.


Article Tags :