- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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 share secondary Y-axis between subplots in Matplotlib?
To share secondary Y-axis between subplots in matplotlib, we can take the following steps −
Create x for data points.
Add a subplot to the current figure, with nrows=2, ncols=1, at index=1 (ax0)
Using twinx() method, create a twin of axes with a shared X-axis but independent Y-axis (ax1).
Add a subplot to the current figure, with nrows=2, ncols=1 at index=2 (ax2)
Using twinx() method, create a twin of axes with a shared X-axis but independent Y-axis (ax3).
Using get_shared_y_axes() method, return a reference to the shared axes Grouper object for Yaxis.
Create curves c1, c2, c3 and c4 with different colors, x and y data points.
To move the legend box to the upper left of the figure, use the legend method with bbox_to_anchor.
To display the figure, use show() method.
import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-2, 2, 10) ax0 = plt.subplot(211) ax1 = ax0.twinx() # Create a twin of Axes with a shared x-axis but independent y-axis. ax2 = plt.subplot(212) ax3 = ax2.twinx() # Create a twin of Axes with a shared x-axis but independent y-axis. ax1.get_shared_y_axes().join(ax1, ax3) c1, = ax0.plot(x, np.sin(x), c='red') c2, = ax1.plot(x, np.cos(x), c='blue') c3, = ax2.plot(x, np.tan(x), c='green') c4, = ax3.plot(x, np.exp(x), c='yellow') plt.legend([c1, c2, c3, c4], ["y=sin(x)", "y=cos(x)", "y=tan(x)", "y=exp(x)"], loc = "upper left", bbox_to_anchor=(.070, 2.25)) plt.show()
- How to plot two Pandas time series on the same plot with legends and secondary Y-axis in Matplotlib?
- How to share x axes of two subplots after they have been created in Matplotlib?
- How to exponentially scale the Y axis with matplotlib?
- Setting the same axis limits for all subplots in Matplotlib
- Setting Y-axis in Matplotlib using Pandas
- How to specify values on Y-axis in Python Matplotlib?
- How to increase the spacing between subplots in Matplotlib with subplot2grid?
- How to change the range of the X-axis and Y-axis in Matplotlib?
- How to force the Y axis to use only integers in Matplotlib?
- How to repress scientific notation in factorplot Y-axis in Seaborn / Matplotlib?
- Overlapping Y-axis tick label and X-axis tick label in Matplotlib
- How to zoom subplots together in Matplotlib/Pyplot?
- How to put gap between Y-axis and the first bar in a vertical barchart in Matplotlib?
- Show the origin axis (x,y) in Matplotlib plot
- How to turn on minor ticks only on the y-axis Matplotlib?