How to align the bar and line in Matplotlib two Y-axes chart?

To align bar and line plots in matplotlib with two Y-axes, we use the twinx() method to create a twin axis that shares the X-axis but has an independent Y-axis. This allows overlaying different chart types on the same plot.

Creating DataFrame and Basic Setup

First, let's create sample data and set up the figure parameters ?

import matplotlib.pyplot as plt
import pandas as pd

# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create sample DataFrame
df = pd.DataFrame({"col1": [1, 3, 5, 7, 1], "col2": [1, 5, 7, 9, 1]})
print(df)
   col1  col2
0     1     1
1     3     5
2     5     7
3     7     9
4     1     1

Plotting Bar Chart with Line Overlay

Now we'll create the bar chart and overlay it with a line chart using twin axes ?

import matplotlib.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]})

# Create bar chart
ax = df.plot(kind="bar")

# Create twin axis for line plot
ax2 = ax.twinx()

# Plot lines on the twin axis
ax2.plot(ax.get_xticks(),
         df[['col1', 'col2']].values,
         linestyle='-',
         marker='o', 
         linewidth=2.0)

plt.show()

How It Works

The alignment works through these key steps:

  • twinx() creates a second Y-axis sharing the same X-axis

  • ax.get_xticks() returns the X-axis tick positions from the bar chart

  • Using these positions ensures the line markers align with bar centers

  • Both plots use the same DataFrame values for consistency

Complete Example with Labels

Here's a more detailed version with proper labels and styling ?

import matplotlib.pyplot as plt
import pandas as pd

# Sample data
data = {"Sales": [100, 150, 120, 200, 180], 
        "Profit": [20, 35, 25, 50, 40]}
df = pd.DataFrame(data)

# Create bar chart
ax1 = df.plot(kind="bar", alpha=0.7, figsize=(8, 5))
ax1.set_ylabel("Sales/Profit Values")
ax1.set_xlabel("Time Period")

# Create twin axis for line plot
ax2 = ax1.twinx()

# Plot lines aligned with bars
ax2.plot(ax1.get_xticks(), df['Sales'].values, 
         'r-o', label='Sales Line', linewidth=2)
ax2.plot(ax1.get_xticks(), df['Profit'].values, 
         'g-s', label='Profit Line', linewidth=2)

ax2.set_ylabel("Line Values")
ax2.legend(loc='upper right')

plt.title("Aligned Bar and Line Chart")
plt.show()

Key Points

  • Use ax.get_xticks() to get exact bar positions for line alignment

  • Twin axes allow independent Y-axis scaling for different data ranges

  • Set different colors and markers to distinguish between chart types

  • Add proper labels and legends for clarity

Conclusion

The twinx() method combined with get_xticks() ensures perfect alignment between bar and line elements. This technique is essential for creating professional dual-axis visualizations in matplotlib.

Updated on: 2026-03-25T21:58:10+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements