How to show a bar and line graph on the same plot in Matplotlib?

To show a bar and line graph on the same plot in Matplotlib, you can combine both plot types using the same axes. This technique is useful for displaying two different data perspectives or comparing trends with categorical data.

Basic Approach

The key steps are ?

  • Create a DataFrame with your data

  • Create a figure and axes using subplots()

  • Plot both bar and line graphs on the same axes

  • Display the combined plot

Example

Here's how to create a combined bar and line plot ?

import pandas as pd
import matplotlib.pyplot as plt

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

# Create sample data
df = pd.DataFrame(dict(data=[2, 4, 1, 5, 9, 6, 0, 7]))

# Create figure and axes
fig, ax = plt.subplots()

# Plot bar chart
df['data'].plot(kind='bar', color='red', alpha=0.7, ax=ax)

# Plot line chart on same axes
df['data'].plot(kind='line', marker='*', color='black', ms=10, ax=ax)

plt.title('Combined Bar and Line Plot')
plt.ylabel('Values')
plt.xlabel('Index')
plt.show()

Using Separate Plot Methods

You can also use plt.bar() and plt.plot() directly ?

import matplotlib.pyplot as plt
import numpy as np

# Sample data
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]

# Create the plot
fig, ax = plt.subplots(figsize=(8, 5))

# Bar chart
bars = ax.bar(categories, values, color='lightblue', alpha=0.7, label='Bars')

# Line chart
line = ax.plot(categories, values, color='red', marker='o', linewidth=2, markersize=8, label='Line')

# Customize the plot
ax.set_title('Bar and Line Chart Combined')
ax.set_ylabel('Values')
ax.set_xlabel('Categories')
ax.legend()
ax.grid(True, alpha=0.3)

plt.show()

Key Points

  • Use the same ax parameter to plot both charts on the same axes

  • Set alpha values to make overlapping elements more visible

  • Add legends to distinguish between bar and line elements

  • Use different colors to make both chart types clearly visible

Conclusion

Combining bar and line plots allows you to show categorical data with trend information in a single visualization. Use the ax parameter to ensure both plots share the same axes, and customize colors and transparency for better readability.

---
Updated on: 2026-03-26T00:18:46+05:30

22K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements