Python’s powerful data visualization libraries, Matplotlib and Seaborn, work seamlessly together. Matplotlib is a low-level library that offers complete control over figure elements, while Seaborn is built on top of Matplotlib and provides a high-level API for attractive and informative statistical graphics. Combining the two allows you to leverage the statistical power and aesthetic enhancements of Seaborn while customizing fine-grained layout details using Matplotlib.
This tutorial explores how to use Matplotlib and Seaborn together to create advanced, customized, and insightful visualizations. You will learn to set styles, create subplots, tweak legends, modify axes, and save figures effectively.
pip install matplotlib seaborn
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
# Sample dataset
np.random.seed(42)
df = pd.DataFrame({
'Category': np.random.choice(['A', 'B', 'C'], size=100),
'Value': np.random.randn(100),
'Group': np.random.choice(['X', 'Y'], size=100)
})
print(df.head())
sns.boxplot(x='Category', y='Value', data=df)
plt.title('Boxplot by Category') # Using Matplotlib to add title
plt.xlabel('Category') # Customize labels with Matplotlib
plt.ylabel('Value')
plt.show()
sns.boxplot(x='Category', y='Value', data=df)
plt.title('Boxplot Saved as PNG')
plt.savefig('boxplot.png', dpi=300)
plt.close()
sns.set_style('whitegrid')
sns.set_context('notebook')
fig, ax = plt.subplots(1, 2, figsize=(12, 5))
sns.boxplot(x='Category', y='Value', data=df, ax=ax[0])
ax[0].set_title('Boxplot')
sns.violinplot(x='Category', y='Value', data=df, ax=ax[1])
ax[1].set_title('Violin Plot')
plt.tight_layout()
plt.show()
ax = sns.boxplot(x='Category', y='Value', data=df)
plt.axhline(0, color='red', linestyle='--') # Matplotlib line
ax.set_title('Boxplot with Zero Reference Line')
plt.show()
ax = sns.barplot(x='Category', y='Value', data=df, ci=None)
ax.set_xticklabels(['Cat A', 'Cat B', 'Cat C'], fontsize=12)
ax.set_yticks(np.arange(-2, 2.5, 0.5))
ax.set_ylabel('Score', fontsize=14)
plt.title('Custom Tick and Label Formatting', fontsize=16)
plt.show()
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
sns.histplot(df[df['Group'] == 'X']['Value'], kde=True, ax=axes[0], color='blue')
axes[0].set_title('Group X Distribution')
sns.histplot(df[df['Group'] == 'Y']['Value'], kde=True, ax=axes[1], color='orange')
axes[1].set_title('Group Y Distribution')
plt.tight_layout()
plt.show()
g = sns.FacetGrid(df, col='Group')
g.map_dataframe(sns.histplot, x='Value', kde=True)
# Add global Matplotlib title
plt.subplots_adjust(top=0.85)
g.fig.suptitle('Distribution by Group')
plt.show()
g = sns.PairGrid(df, hue='Group', vars=['Value'])
g.map_diag(sns.histplot)
g.map_offdiag(sns.scatterplot)
g.add_legend()
# Add Matplotlib style edits
g.fig.suptitle('PairGrid Example', fontsize=16)
plt.subplots_adjust(top=0.9)
plt.show()
sns.set_style('darkgrid')
sns.set_context('talk')
sns.set_palette('Set2')
sns.boxplot(x='Category', y='Value', hue='Group', data=df)
plt.title('Styled Seaborn + Matplotlib Combo')
plt.show()
ax = sns.barplot(x='Category', y='Value', data=df, ci=None)
plt.title('Barplot with Annotations')
# Add annotations using Matplotlib
for i, p in enumerate(ax.patches):
height = p.get_height()
ax.annotate(f'{height:.2f}', (p.get_x() + p.get_width() / 2., height),
ha='center', va='bottom', fontsize=10, color='black')
plt.show()
palette = {'X': 'skyblue', 'Y': 'salmon'}
sns.boxplot(x='Category', y='Value', hue='Group', data=df, palette=palette)
plt.title('Custom Palette by Group')
plt.show()
sns.reset_defaults()
plt.plot([1, 2, 3], [3, 2, 1])
plt.title('Matplotlib Default Style')
plt.show()
sns.boxplot(x='Category', y='Value', data=df)
plt.title('Export Example')
plt.savefig('export_plot.svg', format='svg', dpi=300)
plt.close()
g = sns.FacetGrid(df, col='Group')
g.map_dataframe(sns.histplot, x='Value')
plt.show() # Required after .map_dataframe
fig, ax = plt.subplots()
sns.boxplot(x='Category', y='Value', data=df, ax=ax)
ax.set_title('Correct Title Placement') # Use ax.set_title
plt.show()
iris = sns.load_dataset('iris')
iris.groupby('species').mean().plot(kind='bar')
plt.title('Mean Measurements per Species')
plt.show()
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
sns.despine() # Remove top and right borders
plt.title('Sine Wave with Seaborn Despine')
plt.show()
Combining Seaborn and Matplotlib provides the best of both worlds: Seaborn offers elegant, simple-to-code statistical graphics, while Matplotlib provides complete control over every visual element. Whether you're building simple reports or complex analytical dashboards, the integration of these two libraries allows you to produce publication-quality graphics that are both beautiful and informative.
From customizing titles and axes to creating intricate subplot layouts and exporting high-resolution figures, mastering both libraries will enhance your data storytelling and analysis capabilities.
Use Seaborn for rapid development and aesthetics, and Matplotlib when you need precision control or integration into larger applications.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is ₹5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from ₹3,000 - ₹1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved