How to Create Bar Chart with Line Using Seaborn Matplotlib
🧠 Introduction
Ever looked at a chart and thought, “Wow, that’s both beautiful and insightful”? That’s usually when a bar chart and line chart come together! In this guide, you’ll learn how to create a bar chart with a line using Seaborn and Matplotlib in Python. This combo is perfect for visualizing quantities (bars) and trends (lines) on the same graph.
🔧 Prerequisites
Before we dive in, make sure you have these libraries installed:
pip install matplotlib seaborn pandas
Now import them:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
📊 Understanding Bar and Line Charts
What is a Bar Chart?
Bar charts display quantitative data with rectangular bars. They’re perfect for comparisons.
What is a Line Chart?
Line charts use a line to display patterns over time.Great for time-series data or performance tracking.
Why Combine Both?
When you mix bars (values) with lines (trends), your story becomes clearer. For example, showing monthly sales (bars) and cumulative growth (line) in one view gives context.
📁 Dataset Preparation
Using a Sample Dataset
Let’s use a basic monthly dataset:
data = {
'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
'Sales': [100, 120, 150, 170, 160, 180],
'Growth': [10, 15, 20, 18, 17, 22]
}
df = pd.DataFrame(data)
Creating a Custom Dataset with Pandas
You can also read data from a CSV:
df = pd.read_csv('your_data.csv')
📈 Introduction to Seaborn and Matplotlib
Key Differences
- Seaborn = High-level, beautiful default themes
- Matplotlib = Low-level, complete control
When to Use Which
Use Seaborn for the bar chart and Matplotlib for the line overlay.
🛠️ Step-by-Step Guide to Creating the Chart
Creating the Base Bar Chart
plt.figure(figsize=(10, 6))
sns.barplot(x='Month', y='Sales', data=df, color='skyblue')
Adding the Line Chart
plt.plot(df['Month'], df['Growth'], color='red', marker='o', label='Growth')
Optional: Adding Secondary Axis
fig, ax1 = plt.subplots(figsize=(10, 6))
sns.barplot(x='Month', y='Sales', data=df, ax=ax1, color='skyblue')
ax2 = ax1.twinx()
ax2.plot(df['Month'], df['Growth'], color='red', marker='o', label='Growth')
ax1.set_ylabel('Sales')
ax2.set_ylabel('Growth (%)')
🎨 Customizing Your Charts
Titles and Labels
plt.title('Monthly Sales and Growth')
plt.xlabel('Month')
plt.ylabel('Sales')
Styling and Themes
sns.set_style("whitegrid")
Adding Data Labels
for index, value in enumerate(df['Sales']):
plt.text(index, value + 5, str(value), ha='center')
📊 Handling Multiple Series
Grouped Bar + Line
If you have multiple categories:
sns.barplot(x='Month', y='Sales', hue='Category', data=df)
Then add line:
for cat in df['Category'].unique():
subset = df[df['Category'] == cat]
plt.plot(subset['Month'], subset['Growth'])
Legends and Labels
plt.legend(loc='upper left')
💾 Saving the Plot
Export as Image
plt.savefig('bar_line_chart.png', dpi=300, bbox_inches='tight')
Adjusting Figure Size
Set figure size before plotting:
plt.figure(figsize=(12, 7))
🐞 Common Errors and Fixes
Mismatched Axis Scale
Always normalize or scale your data if one range is too wide compared to another.
Overlapping Plots
Use plt.tight_layout() to fix layout issues.
✅ Best Practices
Chart Readability
- Keep it clean.
- Avoid too many colors.
- Use readable fonts.
Color Combinations
Use:
- Cool color for bars
- Warm color for line
- Match your brand/theme
🌍 Real-World Use Cases
Sales vs. Target
- Bars: Actual sales
- Line: Target goal
Website Traffic Analysis
- Bars: Daily visits
- Line: Conversion rate
🧾 Conclusion
Combining bar and line charts in Python using Seaborn and Matplotlib is a powerful technique for clear, meaningful visualizations. Whether you’re tracking KPIs, analyzing trends, or impressing your boss with data visuals, mastering this combo is a must. Try it out, tweak it, and make your charts speak louder than words!
❓ FAQs
1. How to plot two different datasets on the same chart?
Use twinx() for dual y-axes and make sure both datasets have the same x-axis scale.
2. Can I use Seaborn for both bar and line?
Not always. Seaborn is great for bars, but Matplotlib gives more control for lines.
3. How to add tooltips to charts?
Use mplcursors or plotly for interactive tooltips.
4. How can values be displayed above bars?
Use plt.text() to manually place value labels on bars.
5. What’s the best way to choose colors?
Stick to color palettes from seaborn.color_palette() or use colorblind-friendly palettes for accessibility.