How to Make a Twin Axes Using Python

When working with datasets that have different scales or units, visualizing them on the same plot using python can be challenging. Python’s Matplotlib library offers a powerful solution: twin axes. This feature allows you to plot two datasets with distinct y-axes on the same x-axis, making comparisons intuitive and visually appealing. We’ll walk through the basics of creating twin axes and enhance the plot with professional touches like labels, legends, and grids.

Original Code

Let’s start with a basic example to plot using python sine and cosine functions on twin axes.

Step-by-Step Explanation

import numpy as np  
import matplotlib.pyplot as plt  

# Generate 100 points between 0 and 10  
x = np.linspace(0, 10, 100)  

# Create a figure and one set of axes  
fig, ax1 = plt.subplots()  

# Create a twin of the first axes that shares the same x-axis  
ax2 = ax1.twinx()  

# Plot sin(x) on the first axes in green  
ax1.plot(x, np.sin(x), 'g-', label='sin(x)')  

# Plot cos(x) on the twin axes in blue  
ax2.plot(x, np.cos(x), 'b-', label='cos(x)')  

# Show the plot  
plt.show()  

Breaking Down the Code

  1. Import Libraries:
    • numpy generates numerical data.
    • matplotlib.pyplot handles plotting.
  2. Generate Data:
    • x = np.linspace(0, 10, 100) creates 100 evenly spaced values from 0 to 10.
  3. Create Axes:
    • fig, ax1 = plt.subplots() initializes a figure (fig) and primary y-axis (ax1).
    • ax2 = ax1.twinx() creates a twin y-axis (ax2) sharing the same x-axis.
  4. Plot Functions:
    • ax1.plot(...) plots the sine curve (green) on the primary axis.
    • ax2.plot(...) plots the cosine curve (blue) on the secondary axis.
  5. Display:
    • plt.show() renders the plot.

Result: A plot with two y-axes, one for sine (green) and one for cosine (blue).

Extended Example: Enhancing Readability

Let’s improve the plot by using python adding labels, a title, a grid, and a unified legend.

Enhanced Code

import numpy as np  
import matplotlib.pyplot as plt  

# Generate data  
x = np.linspace(0, 10, 100)  
y_sin = np.sin(x)  
y_cos = np.cos(x)  

# Create figure and axes  
fig, ax1 = plt.subplots(figsize=(8, 5))  
ax2 = ax1.twinx()  

# Plot data  
line1 = ax1.plot(x, y_sin, 'g-', label='sin(x)')  
line2 = ax2.plot(x, y_cos, 'b-', label='cos(x)')  

# Label axes and add title  
ax1.set_xlabel('X values')  
ax1.set_ylabel('Sine', color='green')  
ax2.set_ylabel('Cosine', color='blue')  
plt.title("Twin Axes Example: Sine vs. Cosine")  

# Combine legends  
lines = line1 + line2  
labels = [line.get_label() for line in lines]  
ax1.legend(lines, labels, loc='upper right')  

# Add grid  
ax1.grid(True, linestyle='--', alpha=0.7)  

# Display  
plt.show()  

Key Enhancements Explained

  1. Axis Labels and Title:
    • set_xlabel() and set_ylabel() label the axes.
    • The title clarifies the plot’s purpose.
  2. Combined Legend:
    • Lines from both axes (line1 + line2) are merged into one legend.
    • loc='upper right' places the legend in the top-right corner.
  3. Grid Customization:
    • A dashed grid (linestyle='--') with reduced opacity (alpha=0.7) improves readability without overwhelming the data.
  4. Figure Size:
    • figsize=(8, 5) creates a larger plot for better detail.

Result: A polished, publication-ready plot.

Why Use Twin Axes?

Twin axes are ideal for:

  • Comparing datasets with different units (e.g., temperature vs. precipitation).
  • Visualizing relationships between variables (e.g., stock prices vs. trading volume).
  • Highlighting correlations or discrepancies in scaled data.

Final Thoughts

Twin axes in Matplotlib are a game-changer for multi-variable visualization. By following the steps above, you can create clear, informative plots that highlight the interplay between datasets. Customize colors, grids, and legends to suit your needs, and experiment with real-world data like financial trends or sensor readings.

Related blog posts