- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add a second X-axis in Matplotlib?
We can use the twiny() method to create a second X-axis. Similarly, using twinx, we can create a shared Y-axis.
Steps
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Plot line with lists passed in the argument of plot() method with color="red".
Create a twin of Axes with a shared Y-axis but independent X-axis.
Plot the line on ax2 that is created in step 3.
Adjust the padding between and around subplots.
To show the figure, use plt.show() method.
Example
import matplotlib.pyplot as plt fig, ax1 = plt.subplots() ax1.plot([1, 2, 3, 4, 5], [3, 5, 7, 1, 9], color='red') ax2 = ax1.twiny() ax2.plot([11, 12, 31, 41, 15], [13, 51, 17, 11, 76], color='blue') fig.tight_layout() plt.show()
Output
- Related Articles
- How to add a second X-axis at the bottom of the first one in Matplotlib?
- How to add footnote under the X-axis using Matplotlib?
- How to customize the X-axis in Matplotlib?
- How to customize X-axis ticks in Matplotlib?
- How to set X-axis values in Matplotlib Python?
- How to annotate a range of the X-axis in Matplotlib?
- How to shift a graph along the X-axis in matplotlib?
- How to place X-axis grid over a spectrogram in Python Matplotlib?
- How to change the range of the X-axis and Y-axis in Matplotlib?
- How to append a single labeled tick to X-axis using matplotlib?
- How to show date and time on the X-axis in Matplotlib?
- Aligning table to X-axis using matplotlib Python
- How to remove or hide X-axis labels from a Seaborn / Matplotlib plot?
- How to set my xlabel at the end of X-axis in Matplotlib?
- How to adjust 'tick frequency' in Matplotlib for string X-axis?

Advertisements