Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to plot with different scales in Matplotlib?
When working with data that has vastly different ranges, plotting multiple datasets on the same axes can make one dataset barely visible. Matplotlib provides twinx() and twiny() methods to create dual-axis plots with different scales.
Basic Dual Y-Axis Plot
Here's how to create a plot with two different y-axis scales using twinx() ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data with different ranges
t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t) # Exponential growth (large values)
data2 = np.sin(2 * np.pi * t) # Sine wave (-1 to 1)
# Create the first plot
fig, ax1 = plt.subplots(figsize=(8, 5))
# Plot first dataset on left y-axis
color = 'red'
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Exponential', color=color)
ax1.plot(t, data1, color=color, label='exp(t)')
ax1.tick_params(axis='y', labelcolor=color)
# Create second y-axis sharing the same x-axis
ax2 = ax1.twinx()
# Plot second dataset on right y-axis
color = 'blue'
ax2.set_ylabel('Sine Wave', color=color)
ax2.plot(t, data2, color=color, label='sin(2?t)')
ax2.tick_params(axis='y', labelcolor=color)
plt.title('Dual Y-Axis Plot with Different Scales')
plt.tight_layout()
plt.show()
Dual X-Axis Plot
You can also create dual x-axis plots using twiny() ?
import numpy as np
import matplotlib.pyplot as plt
# Sample data
y = np.linspace(0, 10, 100)
temp_celsius = y * 2 + 20
temp_fahrenheit = temp_celsius * 9/5 + 32
fig, ax1 = plt.subplots(figsize=(8, 5))
# Plot on bottom x-axis (Celsius)
color = 'red'
ax1.set_xlabel('Temperature (°C)', color=color)
ax1.set_ylabel('Height')
ax1.plot(temp_celsius, y, color=color)
ax1.tick_params(axis='x', labelcolor=color)
# Create second x-axis on top (Fahrenheit)
ax2 = ax1.twiny()
color = 'blue'
ax2.set_xlabel('Temperature (°F)', color=color)
ax2.plot(temp_fahrenheit, y, color=color)
ax2.tick_params(axis='x', labelcolor=color)
plt.title('Dual X-Axis Plot: Celsius and Fahrenheit')
plt.tight_layout()
plt.show()
Advanced Dual Axes with Legends
For better visualization, you can add legends and customize the appearance ?
import numpy as np
import matplotlib.pyplot as plt
# Sample data
months = np.arange(1, 13)
sales = [150, 180, 220, 280, 320, 380, 420, 460, 400, 350, 280, 200]
profit_margin = [12, 15, 18, 22, 25, 28, 30, 32, 29, 26, 20, 16]
fig, ax1 = plt.subplots(figsize=(10, 6))
# Plot sales data (left y-axis)
color = 'tab:blue'
ax1.set_xlabel('Month')
ax1.set_ylabel('Sales (thousands)', color=color)
line1 = ax1.plot(months, sales, color=color, marker='o', linewidth=2, label='Sales')
ax1.tick_params(axis='y', labelcolor=color)
ax1.grid(True, alpha=0.3)
# Create second y-axis for profit margin
ax2 = ax1.twinx()
color = 'tab:red'
ax2.set_ylabel('Profit Margin (%)', color=color)
line2 = ax2.plot(months, profit_margin, color=color, marker='s', linewidth=2, label='Profit Margin')
ax2.tick_params(axis='y', labelcolor=color)
# Add combined legend
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')
plt.title('Monthly Sales and Profit Margin')
plt.tight_layout()
plt.show()
Key Methods
| Method | Purpose | Usage |
|---|---|---|
twinx() |
Create twin y-axis | Different y-scale ranges |
twiny() |
Create twin x-axis | Different x-scale units |
tick_params() |
Style axis ticks | Color coordination |
Conclusion
Use twinx() for dual y-axis plots when datasets have different value ranges. This technique allows effective comparison of related data with vastly different scales on the same plot.
Advertisements
