Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can bar plot be used in Seaborn library in Python?
Seaborn is a powerful Python library for statistical data visualization built on matplotlib. It comes with customized themes and provides a high-level interface for creating attractive statistical graphics.
Bar plots in Seaborn help us understand the central tendency of data distributions by showing the relationship between a categorical variable and a continuous variable. The barplot() function displays data as rectangular bars where the height represents the mean value of the continuous variable for each category.
Basic Syntax
seaborn.barplot(x=None, y=None, hue=None, data=None, estimator=numpy.mean, ci=95)
Key Parameters
- x, y: Column names for categorical and continuous variables
- hue: Additional categorical variable for grouping
- data: DataFrame containing the data
- estimator: Statistical function (default: mean)
- ci: Confidence interval size (default: 95%)
Example with Titanic Dataset
Let's create a bar plot showing survival rates by gender and passenger class using the Titanic dataset ?
import pandas as pd
import seaborn as sb
import matplotlib.pyplot as plt
# Load the titanic dataset
titanic_data = sb.load_dataset('titanic')
# Create bar plot
plt.figure(figsize=(8, 6))
sb.barplot(x="sex", y="survived", hue="class", data=titanic_data)
plt.title('Survival Rate by Gender and Class')
plt.ylabel('Survival Rate')
plt.xlabel('Gender')
plt.show()
Simple Bar Plot
Here's a basic bar plot showing average survival rate by gender ?
import seaborn as sb
import matplotlib.pyplot as plt
# Load dataset
titanic_data = sb.load_dataset('titanic')
# Simple bar plot
plt.figure(figsize=(6, 4))
sb.barplot(x="sex", y="survived", data=titanic_data)
plt.title('Average Survival Rate by Gender')
plt.ylabel('Survival Rate')
plt.show()
Customizing Bar Plots
You can customize colors, add error bars, and change the estimator function ?
import seaborn as sb
import matplotlib.pyplot as plt
import numpy as np
# Load dataset
titanic_data = sb.load_dataset('titanic')
# Customized bar plot
plt.figure(figsize=(10, 6))
sb.barplot(x="class", y="fare", data=titanic_data,
estimator=np.median, ci=None, palette="viridis")
plt.title('Median Fare by Passenger Class')
plt.ylabel('Median Fare')
plt.xlabel('Passenger Class')
plt.show()
Key Features
| Feature | Description | Default Value |
|---|---|---|
| Estimator | Statistical function applied | Mean |
| Error bars | Shows confidence intervals | 95% CI |
| Grouping | Multiple categories with hue | None |
Conclusion
Seaborn's barplot() function is ideal for comparing mean values across categories. It automatically calculates confidence intervals and provides elegant styling, making it perfect for exploratory data analysis and presentations.
