Plotting with Seaborn and Matplotlib
Last Updated :
23 Jul, 2025
Matplotlib and Seaborn are two of the most powerful Python libraries for data visualization. While Matplotlib provides a low-level, flexible approach to plotting, Seaborn simplifies the process by offering built-in themes and functions for common plots.
Before diving into plotting, ensure you have both libraries installed:
pip install matplotlib seaborn
After installation, Import them in your script:
import matplotlib.pyplot as plt
import seaborn as sns
Basic plotting with matplotlib
Matplotlib allows you to create simple plots using plt.plot(). Here’s an example of plotting lines and dots:
Python
import matplotlib.pyplot as plt
plt.plot([0, 1], [10, 11], label='Line 1')
plt.plot([0, 1], [11, 10], label='Line 2')
plt.scatter([0, 1], [10.5, 10.5], color='blue', marker='o', label='Dots')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line and Dot Plot')
plt.legend()
plt.show()
Explanation:
- plt.plot([0, 1], [10, 11], label='Line 1') plots a line moving upward from (0,10) to (1,11).
- plt.plot([0, 1], [11, 10], label='Line 2') plots a line moving downward from (0,11) to (1,10).
- label='Line 1' / 'Line 2' assigns names for the legend.
Why Combine matplotlib and seaborn?
Seaborn makes plotting easier, but it is built on top of Matplotlib, so we can use both together for better results:
- Customization: Matplotlib lets us fully control the plot (axes, labels, grid, colors, etc.).
- Better Looks: Seaborn has built-in themes and styles that make plots look nicer.
- Statistical Plots: Seaborn includes special plots like violin plots and KDE plots.
- More Flexibility: Matplotlib allows extra customization and combining multiple plots.
Enhancing matplotlib with seaborn styles
Seaborn simplifies data visualization with built-in themes and high-level functions.
Example 1. Applying seaborn style to matplotlib plots
Python
import matplotlib.pyplot as plt
import seaborn as sns
# Apply Seaborn theme
sns.set_theme(style="darkgrid")
# Creating a simple Matplotlib plot
x = [1, 2, 3, 4, 5]
y = [10, 12, 15, 18, 22]
plt.plot(x, y, marker='o', linestyle='-', color='blue', label="Trend")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Matplotlib Plot with Seaborn Theme")
plt.legend()
plt.show()
Output:
Explanation:
- sns.set_theme(style="darkgrid") applies a Seaborn theme for a cleaner look.
- The plot consists of a simple line with markers, enhanced with labels and a legend.
Example 2. Customizing a seaborn plot with matplotlib
Python
import matplotlib.pyplot as plt
import seaborn as sns
import panda as pd
data = pd.DataFrame({
'Year': [2018, 2019, 2020, 2021, 2022],
'Sales': [100, 150, 200, 250, 300]
})
plt.figure(figsize=(8, 5))
sns.lineplot(x='Year', y='Sales', data=data, marker='o')
# Customizing using Matplotlib
plt.title("Yearly Sales Growth", fontsize=14, fontweight='bold')
plt.xlabel("Year", fontsize=12)
plt.ylabel("Total Sales", fontsize=12)
plt.xticks(rotation=45)
plt.grid(True, linestyle='--')
plt.show()
Output:
Explanation:
- Seaborn’s sns.lineplot() creates a line plot from a DataFrame.
- Matplotlib functions customize the title, axis labels and grid styling.
Example 3. Overlaying seaborn and matplotlib plots
Python
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.linspace(0, 10, 20)
y = np.sin(x)
plt.figure(figsize=(8, 5))
# Seaborn Line Plot
sns.lineplot(x=x, y=y, color='blue', label='Sine Wave')
# Matplotlib Scatter Plot
plt.scatter(x, y, color='red', marker='o', label="Data Points")
plt.title("Seaborn Line Plot with Matplotlib Scatter Overlay")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.show()
Output:
Explanation:
- sns.lineplot() creates a smooth sine wave.
- plt.scatter() overlays red data points for better visualization.
Example 4. Enhancing Seaborn Histogram with Matplotlib Annotations
Python
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.random.randn(1000)
plt.figure(figsize=(8, 5))
sns.histplot(data, kde=True, bins=30, color='purple')
# Adding Mean Line using Matplotlib
mean_value = np.mean(data)
plt.axvline(mean_value, color='red', linestyle='dashed', linewidth=2)
plt.text(mean_value + 0.1, 50, f'Mean: {mean_value:.2f}', color='red')
plt.title("Distribution with Seaborn and Matplotlib Customization")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
Output:
Explanation:
- sns.histplot() creates a histogram with a KDE curve.
- plt.axvline() draws a dashed red line at the mean value.
- plt.text() annotates the mean value on the plot.
Similar Reads
Python - Data visualization tutorial Data visualization is the process of converting complex data into graphical formats such as charts, graphs, and maps. It allows users to understand patterns, trends, and outliers in large datasets quickly and clearly. By transforming data into visual elements, data visualization helps in making data
5 min read
What is Data Visualization and Why is It Important? Data visualization uses charts, graphs and maps to present information clearly and simply. It turns complex data into visuals that are easy to understand.With large amounts of data in every industry, visualization helps spot patterns and trends quickly, leading to faster and smarter decisions.Common
4 min read
Data Visualization using Matplotlib in Python Matplotlib is a widely-used Python library used for creating static, animated and interactive data visualizations. It is built on the top of NumPy and it can easily handles large datasets for creating various types of plots such as line charts, bar charts, scatter plots, etc. Visualizing Data with P
11 min read
Data Visualization with Seaborn - Python Seaborn is a popular Python library for creating attractive statistical visualizations. Built on Matplotlib and integrated with Pandas, it simplifies complex plots like line charts, heatmaps and violin plots with minimal code.Creating Plots with SeabornSeaborn makes it easy to create clear and infor
9 min read
Data Visualization with Pandas Pandas is a powerful open-source data analysis and manipulation library for Python. The library is particularly well-suited for handling labeled data such as tables with rows and columns. Pandas allows to create various graphs directly from your data using built-in functions. This tutorial covers Pa
6 min read
Plotly for Data Visualization in Python Plotly is an open-source Python library designed to create interactive, visually appealing charts and graphs. It helps users to explore data through features like zooming, additional details and clicking for deeper insights. It handles the interactivity with JavaScript behind the scenes so that we c
12 min read
Data Visualization using Plotnine and ggplot2 in Python Plotnine is a Python data visualization library built on the principles of the Grammar of Graphics, the same philosophy that powers ggplot2 in R. It allows users to create complex plots by layering components such as data, aesthetics and geometric objects.Installing Plotnine in PythonThe plotnine is
6 min read
Introduction to Altair in Python Altair is a declarative statistical visualization library in Python, designed to make it easy to create clear and informative graphics with minimal code. Built on top of Vega-Lite, Altair focuses on simplicity, readability and efficiency, making it a favorite among data scientists and analysts.Why U
4 min read
Python - Data visualization using Bokeh Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots. Bokeh output can be obtained in various mediums like notebook, html and server. It is possible to embed bokeh plots in Django and flask apps. Bokeh provides two visualization interfaces to us
4 min read
Pygal Introduction Python has become one of the most popular programming languages for data science because of its vast collection of libraries. In data science, data visualization plays a crucial role that helps us to make it easier to identify trends, patterns, and outliers in large data sets. Pygal is best suited f
5 min read