While working on a data visualization project in Python, I needed to invert the secondary Y-axis in a Matplotlib chart. At first, I thought it would be as simple as flipping the main Y-axis, but I quickly realized the secondary axis behaves differently.
In this tutorial, I’ll walk you through how to invert the secondary Y-axis in Matplotlib using Python. I’ll cover multiple methods, explain how each one works, and share full working code examples that you can try right away.
If you’ve ever worked with dual-axis charts in Python, you’ll know they’re incredibly useful when comparing two datasets with different scales.
What is a Secondary Y-Axis in Matplotlib?
In Matplotlib, the secondary Y-axis is an additional vertical axis that appears on the right-hand side of the plot. It allows you to display a second dataset that has a different scale from the main Y-axis.
For instance, you might want to plot temperature (°F) on the left axis and humidity (%) on the right axis. This dual-axis setup helps you visualize relationships between two variables that share the same X-axis but differ in units or magnitude.
Invert the Secondary Y-Axis in Python
There are several real-world cases where inverting the secondary Y-axis makes sense.
For example:
- When plotting altitude (higher values should appear lower on the graph).
- When showing depth in oceanography or geology (depth increases downward).
- When displaying financial decay or negative correlation trends.
In Python’s Matplotlib, you can easily invert an axis using the invert_yaxis() method.
However, when dealing with a secondary Y-axis, you need to apply this method to the correct axis object.
Let’s go through the methods now.
Method 1: Invert Secondary Y-Axis using twinx() in Python
The simplest way to create and invert a secondary Y-axis in Matplotlib is by utilizing the twinx() function. This function creates a second Y-axis that shares the same X-axis as the original plot.
Here’s how I do it in Python.
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
temperature = np.sin(x) * 20 + 70 # Temperature in °F
altitude = np.linspace(0, 10000, 100) # Altitude in feet
# Create main plot
fig, ax1 = plt.subplots(figsize=(8, 5))
ax1.plot(x, temperature, color='tab:red', label='Temperature (°F)')
ax1.set_xlabel('Time (hours)')
ax1.set_ylabel('Temperature (°F)', color='tab:red')
# Create secondary Y-axis
ax2 = ax1.twinx()
ax2.plot(x, altitude, color='tab:blue', label='Altitude (ft)')
ax2.set_ylabel('Altitude (ft)', color='tab:blue')
# Invert the secondary Y-axis
ax2.invert_yaxis()
# Add title and grid
plt.title('Temperature vs Altitude Over Time')
ax1.grid(True)
plt.show()You can see the output in the screenshot below.

In this Python example, I first plotted temperature data on the main Y-axis and altitude on the secondary Y-axis. Then, I used ax2.invert_yaxis() to flip the secondary axis so that higher altitudes appear lower on the chart.
This method is quick, simple, and perfect for most dual-axis visualization needs in Python.
Method 2: Invert Secondary Y-Axis using secondary_yaxis() in Python
Starting from Matplotlib version 3.1, you can use the secondary_yaxis() method to create a more flexible secondary Y-axis. This method gives you more control over transformations and scaling.
Here’s how I use it in Python.
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
pressure = np.exp(-x / 3) * 100 # Pressure in PSI
depth = np.linspace(0, 5000, 100) # Depth in feet
# Create the main plot
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(x, pressure, color='tab:green', label='Pressure (PSI)')
ax.set_xlabel('Time (hours)')
ax.set_ylabel('Pressure (PSI)', color='tab:green')
# Create the secondary Y-axis
def depth_to_pressure(y):
return 100 - (y / 50)
def pressure_to_depth(y):
return (100 - y) * 50
secax = ax.secondary_yaxis('right', functions=(depth_to_pressure, pressure_to_depth))
secax.set_ylabel('Depth (ft)', color='tab:blue')
# Invert the secondary Y-axis
secax.invert_yaxis()
plt.title('Pressure vs Depth Over Time')
ax.grid(True)
plt.show()You can see the output in the screenshot below.

In this Python example, I used transformation functions to define how pressure relates to depth. Then, I inverted the secondary Y-axis using invert_yaxis() to make the depth values increase downward.
This method is ideal when you need mathematical relationships between the two axes.
Method 3: Invert Both Y-Axes Simultaneously in Python
Sometimes, you might want to invert both the primary and secondary Y-axes for a mirrored visualization. This can be useful when comparing opposing trends, such as gain vs. loss or temperature rise vs. fall.
Here’s how you can achieve that in Python.
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
gain = np.cos(x) * 50 + 100
loss = np.sin(x) * 30 + 50
# Create main plot
fig, ax1 = plt.subplots(figsize=(8, 5))
ax1.plot(x, gain, color='tab:orange', label='Gain')
ax1.set_xlabel('Time (months)')
ax1.set_ylabel('Gain', color='tab:orange')
# Create secondary Y-axis
ax2 = ax1.twinx()
ax2.plot(x, loss, color='tab:purple', label='Loss')
ax2.set_ylabel('Loss', color='tab:purple')
# Invert both Y-axes
ax1.invert_yaxis()
ax2.invert_yaxis()
plt.title('Gain vs Loss (Inverted Y-Axes)')
ax1.grid(True)
plt.show()You can see the output in the screenshot below.

In this Python code, both axes are inverted to display mirrored data trends. This approach works well for visual comparisons where increasing one variable means decreasing another.
Tips for Using Inverted Secondary Y-Axis in Python
Here are a few quick tips I’ve learned from experience when working with inverted secondary Y-axes in Matplotlib:
- Always label your axes clearly, especially when one of them is inverted.
- Use contrasting colors for primary and secondary data to avoid confusion.
- If you’re using logarithmic scales, call set_yscale(‘log’) before inverting the axis.
- Remember that invert_yaxis() only affects the visual direction; it doesn’t change your data values.
These small adjustments can make a big difference in readability and accuracy.
Common Mistakes to Avoid
When I first started using inverted axes in Python, I made a few mistakes that confused my plots.
Here are some pitfalls to avoid:
- Inverting the wrong axis object – Always ensure you’re calling invert_yaxis() on the correct axis (ax2 for secondary).
- Forgetting to reapply inversion after updates – If you redraw or update the plot, you may need to reapply the inversion.
- Neglecting axis limits – Use set_ylim() if you need to control the range after inversion.
- Not adding legends – Always include legends to clarify which dataset belongs to which axis.
Avoiding these mistakes will save you a lot of debugging time.
Real-World Example: Visualize Temperature vs. Altitude in the USA
Let’s take a practical example relevant to the USA. Imagine you’re analyzing temperature changes with altitude across the Rocky Mountains.
Here’s how you can visualize it in Python using an inverted secondary Y-axis.
import matplotlib.pyplot as plt
import numpy as np
# Simulated data for the Rocky Mountains
altitude = np.linspace(0, 14000, 100) # in feet
temperature = 70 - (altitude / 1000) * 3.5 # °F decrease per 1000 ft
time = np.linspace(0, 24, 100) # hours
fig, ax1 = plt.subplots(figsize=(9, 5))
ax1.plot(time, temperature, color='tab:red', label='Temperature (°F)')
ax1.set_xlabel('Time of Day (hours)')
ax1.set_ylabel('Temperature (°F)', color='tab:red')
ax2 = ax1.twinx()
ax2.plot(time, altitude, color='tab:blue', label='Altitude (ft)')
ax2.set_ylabel('Altitude (ft)', color='tab:blue')
# Invert the secondary Y-axis
ax2.invert_yaxis()
plt.title('Temperature vs Altitude in the Rocky Mountains (USA)')
ax1.grid(True)
plt.show()In this Python example, you can see how the temperature decreases with increasing altitude. By inverting the secondary Y-axis, the visualization feels more natural; higher altitudes appear lower on the chart.
Conclusion
Inverting the secondary Y-axis in Matplotlib using Python is a simple yet powerful technique. It allows you to create more meaningful and intuitive visualizations, especially when dealing with datasets like altitude, depth, or decay.
I’ve shown you three methods:
- Using twinx()
- Using secondary_yaxis()
- Inverting both Y-axes together
Each method has its own advantages, and I recommend trying them out to see which one fits your use case best.
You may also like to read:
- Flip Y-Axis Label in Matplotlib using Python
- Invert the Y-Axis in Matplotlib imshow
- Create Two Y Axes Bar Plot in Matplotlib
- Invert the Y-Axis in 3D Plot using Matplotlib

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.