- 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 align the bar and line in Matplotlib two Y-axes chart?
To align the bar and line in matplotlib two Y-axes chart, we can use twinx() method to create a twin of Axes with a shared X-axis but independent Y-axis.
Steps
Set the figure size and adjust the padding between and around the subplots.
Make a Pandas dataframe with columns 1 and 2.
Plot the dataframe using plot() method with kind="bar", i.e., class by name.
Use twinx() method to create a twin of Axes with a shared X-axis but independent Y-axis.
Plot the axis (Step 3) ticks and dataframe columns values to plot the lines.
To display the figure, use show() method.
Example
from matplotlib import pyplot as plt import pandas as pd plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame({"col1": [1, 3, 5, 7, 1], "col2": [1, 5, 7, 9, 1]}) ax = df.plot(kind="bar") ax2 = ax.twinx() ax2.plot(ax.get_xticks(), df[['col1', 'col2']].values, linestyle='-', marker='o', linewidth=2.0) plt.show()
Output
- Related Articles
- How to increase the thickness of error line in a Matplotlib bar chart?
- How to create a Matplotlib bar chart with a threshold line?
- How to plot single data with two Y-axes (two units) in Matplotlib?
- How to change Bar Chart values to percentages in Matplotlib?
- Horizontal stacked bar chart in Matplotlib
- How to display stacked bar chart using matplotlib in Python?
- How to display percentage above a bar chart in Matplotlib?
- How to Create a Diverging Stacked Bar Chart in Matplotlib?
- How to remove gaps between bars in Matplotlib bar chart?
- How to determine the order of bars in a matplotlib bar chart?
- How to plot a Bar Chart with multiple labels in Matplotlib?
- How to create a line chart using Matplotlib?
- How to Add Vertical/Average Line to Bar Chart in Excel?
- How to plot a bar chart for a list in Python matplotlib?
- How to sort bars in increasing order in a bar chart in matplotlib?

Advertisements