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 single data with two Y-axes (two units) in Matplotlib?
To plot single data with two Y-axes (two units) in Matplotlib, you can use twinx() to create a secondary Y-axis that shares the same X-axis. This is useful when plotting two datasets with different units or scales.
Basic Setup
First, let's understand the key steps ?
- Create the primary plot with the first dataset
- Use
twinx()to create a twin Y-axis - Plot the second dataset on the twin axis
- Add appropriate labels and legends
Example
Here's a complete example plotting speed and acceleration with different Y-axis scales ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create sample data
speed = np.array([3, 1, 2, 0, 5])
acceleration = np.array([6, 5, 7, 1, 5])
# Create the first plot
ax1 = plt.subplot()
l1, = ax1.plot(speed, color='red', marker='o')
ax1.set_ylabel('Speed (m/s)', color='red')
ax1.tick_params(axis='y', labelcolor='red')
# Create twin axis
ax2 = ax1.twinx()
l2, = ax2.plot(acceleration, color='orange', marker='s')
ax2.set_ylabel('Acceleration (m/s²)', color='orange')
ax2.tick_params(axis='y', labelcolor='orange')
# Add labels and legend
ax1.set_xlabel('Time')
plt.legend([l1, l2], ["Speed", "Acceleration"], loc='upper right')
plt.show()
Advanced Example with Different Scales
When datasets have very different ranges, dual Y-axes become essential ?
import matplotlib.pyplot as plt
import numpy as np
# Create data with different scales
time = np.arange(0, 10, 0.5)
temperature = 20 + 10 * np.sin(time) # Temperature in Celsius
pressure = 1000 + 50 * np.cos(time) # Pressure in hPa
fig, ax1 = plt.subplots(figsize=(10, 6))
# Plot temperature on primary y-axis
color = 'tab:red'
ax1.set_xlabel('Time (hours)')
ax1.set_ylabel('Temperature (°C)', color=color)
line1 = ax1.plot(time, temperature, color=color, linewidth=2, label='Temperature')
ax1.tick_params(axis='y', labelcolor=color)
ax1.grid(True, alpha=0.3)
# Create secondary y-axis for pressure
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('Pressure (hPa)', color=color)
line2 = ax2.plot(time, pressure, color=color, linewidth=2, linestyle='--', label='Pressure')
ax2.tick_params(axis='y', labelcolor=color)
# Combine legends
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('Temperature and Pressure Over Time')
plt.tight_layout()
plt.show()
Key Methods
| Method | Purpose | Usage |
|---|---|---|
twinx() |
Creates twin Y-axis | ax2 = ax1.twinx() |
set_ylabel() |
Sets Y-axis label | ax1.set_ylabel('Label', color='red') |
tick_params() |
Customizes tick appearance | ax1.tick_params(axis='y', labelcolor='red') |
Best Practices
When using dual Y-axes, follow these guidelines ?
- Use different colors for each axis and corresponding data
- Include clear labels with units
- Make tick labels match the line colors
- Combine legends from both axes
- Consider if the data truly needs different scales
Conclusion
Dual Y-axes in Matplotlib are created using twinx() method. Use different colors for each axis and ensure clear labeling to avoid confusion. This technique is perfect for comparing datasets with different units or scales.
Advertisements
