Python - Combining Matplotlib and Seaborn

Python - Combining Matplotlib and Seaborn

Combining Matplotlib and Seaborn in Python

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.

1. Getting Started

1.1 Installing Libraries

pip install matplotlib seaborn

1.2 Importing Required Modules

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

1.3 Creating a Sample Dataset

# 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())

2. Basic Seaborn Plot with Matplotlib Customization

2.1 Create a Seaborn Boxplot

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()

2.2 Save Figure Using Matplotlib

sns.boxplot(x='Category', y='Value', data=df)
plt.title('Boxplot Saved as PNG')
plt.savefig('boxplot.png', dpi=300)
plt.close()

3. Seaborn Styles + Matplotlib Custom Layouts

3.1 Applying Seaborn Styles Globally

sns.set_style('whitegrid')
sns.set_context('notebook')

3.2 Using Subplots from Matplotlib

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()

4. Combining Seaborn’s Power with Matplotlib Precision

4.1 Add Horizontal Line to Seaborn Plot Using Matplotlib

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()

4.2 Customize Ticks, Legends, and Fonts

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()

5. Multiple Plots with Shared Data Context

5.1 Faceted Plots Using Matplotlib Subplots

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()

6. Using Seaborn FacetGrid with Matplotlib

6.1 FacetGrid Overview

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()

7. Pairing Plot Types and Custom Axes

7.1 PairGrid with Line and Scatter

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()

8. Advanced Aesthetics

8.1 Set Global Themes

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()

8.2 Add Annotations

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()

9. Working with Color Palettes

9.1 Set Custom Color Palette

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()

9.2 Revert to Matplotlib Defaults

sns.reset_defaults()
plt.plot([1, 2, 3], [3, 2, 1])
plt.title('Matplotlib Default Style')
plt.show()

10. Exporting High-Quality Visuals

10.1 Save in Different Formats

sns.boxplot(x='Category', y='Value', data=df)
plt.title('Export Example')
plt.savefig('export_plot.svg', format='svg', dpi=300)
plt.close()

11. Common Mistakes and Fixes

11.1 Using plt.show() after sns.FacetGrid

g = sns.FacetGrid(df, col='Group')
g.map_dataframe(sns.histplot, x='Value')
plt.show()  # Required after .map_dataframe

11.2 Misaligned Titles or Labels

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()

12. Use Cases and Applications

  • Exploratory Data Analysis (EDA): Use Seaborn to quickly understand distributions, Matplotlib for custom annotations or layout.
  • Scientific Publications: Seaborn provides visually appealing defaults; Matplotlib gives control over figure aesthetics, resolution, fonts, and export.
  • Dashboards: Matplotlib helps embed Seaborn plots into GUIs or web dashboards (e.g., Dash, Streamlit).
  • Animation: Matplotlib’s animation module can be used with Seaborn plots for time-series visualizations.

13. Combining with Other Libraries

13.1 With Pandas

iris = sns.load_dataset('iris')
iris.groupby('species').mean().plot(kind='bar')
plt.title('Mean Measurements per Species')
plt.show()

13.2 With NumPy Arrays

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.

Beginner 5 Hours
Python - Combining Matplotlib and Seaborn

Combining Matplotlib and Seaborn in Python

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.

1. Getting Started

1.1 Installing Libraries

pip install matplotlib seaborn

1.2 Importing Required Modules

import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np

1.3 Creating a Sample Dataset

# 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())

2. Basic Seaborn Plot with Matplotlib Customization

2.1 Create a Seaborn Boxplot

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()

2.2 Save Figure Using Matplotlib

sns.boxplot(x='Category', y='Value', data=df) plt.title('Boxplot Saved as PNG') plt.savefig('boxplot.png', dpi=300) plt.close()

3. Seaborn Styles + Matplotlib Custom Layouts

3.1 Applying Seaborn Styles Globally

sns.set_style('whitegrid') sns.set_context('notebook')

3.2 Using Subplots from Matplotlib

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()

4. Combining Seaborn’s Power with Matplotlib Precision

4.1 Add Horizontal Line to Seaborn Plot Using Matplotlib

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()

4.2 Customize Ticks, Legends, and Fonts

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()

5. Multiple Plots with Shared Data Context

5.1 Faceted Plots Using Matplotlib Subplots

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()

6. Using Seaborn FacetGrid with Matplotlib

6.1 FacetGrid Overview

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()

7. Pairing Plot Types and Custom Axes

7.1 PairGrid with Line and Scatter

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()

8. Advanced Aesthetics

8.1 Set Global Themes

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()

8.2 Add Annotations

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()

9. Working with Color Palettes

9.1 Set Custom Color Palette

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()

9.2 Revert to Matplotlib Defaults

sns.reset_defaults() plt.plot([1, 2, 3], [3, 2, 1]) plt.title('Matplotlib Default Style') plt.show()

10. Exporting High-Quality Visuals

10.1 Save in Different Formats

sns.boxplot(x='Category', y='Value', data=df) plt.title('Export Example') plt.savefig('export_plot.svg', format='svg', dpi=300) plt.close()

11. Common Mistakes and Fixes

11.1 Using plt.show() after sns.FacetGrid

g = sns.FacetGrid(df, col='Group') g.map_dataframe(sns.histplot, x='Value') plt.show() # Required after .map_dataframe

11.2 Misaligned Titles or Labels

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()

12. Use Cases and Applications

  • Exploratory Data Analysis (EDA): Use Seaborn to quickly understand distributions, Matplotlib for custom annotations or layout.
  • Scientific Publications: Seaborn provides visually appealing defaults; Matplotlib gives control over figure aesthetics, resolution, fonts, and export.
  • Dashboards: Matplotlib helps embed Seaborn plots into GUIs or web dashboards (e.g., Dash, Streamlit).
  • Animation: Matplotlib’s animation module can be used with Seaborn plots for time-series visualizations.

13. Combining with Other Libraries

13.1 With Pandas

iris = sns.load_dataset('iris') iris.groupby('species').mean().plot(kind='bar') plt.title('Mean Measurements per Species') plt.show()

13.2 With NumPy Arrays

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.

Frequently Asked Questions for Python

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.


Python's syntax is a lot closer to English and so it is easier to read and write, making it the simplest type of code to learn how to write and develop with. The readability of C++ code is weak in comparison and it is known as being a language that is a lot harder to get to grips with.

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. Performance: Java has a higher performance than Python due to its static typing and optimization by the Java Virtual Machine (JVM).

Python can be considered beginner-friendly, as it is a programming language that prioritizes readability, making it easier to understand and use. Its syntax has similarities with the English language, making it easy for novice programmers to leap into the world of development.

To start coding in Python, you need to install Python and set up your development environment. You can download Python from the official website, use Anaconda Python, or start with DataLab to get started with Python in your browser.

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.

Python alone isn't going to get you a job unless you are extremely good at it. Not that you shouldn't learn it: it's a great skill to have since python can pretty much do anything and coding it is fast and easy. It's also a great first programming language according to lots of programmers.

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

  • Choose Your Focus. Python is a versatile language with a wide range of applications, from web development and data analysis to machine learning and artificial intelligence.
  • Practice regularly.
  • Work on real projects.
  • Join a community.
  • Don't rush.
  • Keep iterating.

The following is a step-by-step guide for beginners interested in learning Python using Windows.

  • Set up your development environment.
  • Install Python.
  • Install Visual Studio Code.
  • Install Git (optional)
  • Hello World tutorial for some Python basics.
  • Hello World tutorial for using Python with VS Code.

Best YouTube Channels to Learn Python

  • Corey Schafer.
  • sentdex.
  • Real Python.
  • Clever Programmer.
  • CS Dojo (YK)
  • Programming with Mosh.
  • Tech With Tim.
  • Traversy Media.

Python can be written on any computer or device that has a Python interpreter installed, including desktop computers, servers, tablets, and even smartphones. However, a laptop or desktop computer is often the most convenient and efficient option for coding due to its larger screen, keyboard, and mouse.

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.

  • Google's Python Class.
  • Microsoft's Introduction to Python Course.
  • Introduction to Python Programming by Udemy.
  • Learn Python - Full Course for Beginners by freeCodeCamp.
  • Learn Python 3 From Scratch by Educative.
  • Python for Everybody by Coursera.
  • Learn Python 2 by Codecademy.

  • Understand why you're learning Python. Firstly, it's important to figure out your motivations for wanting to learn Python.
  • Get started with the Python basics.
  • Master intermediate Python concepts.
  • Learn by doing.
  • Build a portfolio of projects.
  • Keep challenging yourself.

Top 5 Python Certifications - Best of 2024
  • PCEP (Certified Entry-level Python Programmer)
  • PCAP (Certified Associate in Python Programmer)
  • PCPP1 & PCPP2 (Certified Professional in Python Programming 1 & 2)
  • Certified Expert in Python Programming (CEPP)
  • Introduction to Programming Using Python by Microsoft.

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.

The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python website, https://www.python.org/, and may be freely distributed.

If you're looking for a lucrative and in-demand career path, you can't go wrong with Python. As one of the fastest-growing programming languages in the world, Python is an essential tool for businesses of all sizes and industries. Python is one of the most popular programming languages in the world today.

line

Copyrights © 2024 letsupdateskills All rights reserved