100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
HomeBlogMatplotlib and Seaborn: Data Visualisation in Python
Data Science

Matplotlib and Seaborn: Data Visualisation in Python

SV

SkillVeris Team

Data Science Team

May 9, 2026 10 min read
Share:
Matplotlib and Seaborn: Data Visualisation in Python
Key Takeaway

Matplotlib gives you full control, while Seaborn gives you beautiful statistical charts in a single line.

In this guide, you'll learn:

  • Always create axes explicitly with fig, ax = plt.subplots(), then call methods on ax.
  • Add a title, axis labels, and a legend on every chart so the insight reads clearly.
  • Use Seaborn for statistical plots like distributions, regressions, and pair plots.
  • Use heatmaps with annot=True to surface correlation matrices during exploratory data analysis.

1Why Visualisation Matters

A table of numbers is hard to understand. A chart of the same numbers often makes the pattern immediately obvious. Good data visualisation is not decorative — it's the difference between an insight being acted on or ignored.

This guide covers the two most important Python visualisation libraries: matplotlib (the foundation, full control) and Seaborn (beautiful statistical charts with one line of code).

Imports

The standard imports used throughout this guide.

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

2Matplotlib Architecture

Matplotlib has a hierarchy: a Figure (the whole canvas) contains Axes (an individual plot area). Always create both explicitly.

Avoid the plt.plot() shortcut for anything beyond quick exploration — the explicit fig, ax approach works in loops, subplots, and saved figures without confusion.

Figure and Axes

Create the figure and axes, plot on the axes, then add a grid of subplots.

code
# Create figure and axes
fig, ax = plt.subplots(figsize=(10, 6))
# Plot on the axes
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title("My First Chart")
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
plt.tight_layout()
plt.show()
# Multiple subplots in a grid
fig, axes = plt.subplots(2, 3, figsize=(15, 8))
# axes is a 2x3 array; axes[0,0] is top-left, axes[1,2] is bottom-right

3Line Charts

Line charts show trends over time. Plot multiple series with distinct markers, colours, and labels, then add a legend and a light grid for readability.

Choosing the right chart type is the first decision in every visualisation.
Choosing the right chart type is the first decision in every visualisation.

Monthly Sales Comparison

Plot two product series with markers, labels, and a horizontal grid.

code
# Monthly sales data
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
sales_a = [120, 145, 132, 178, 190, 210]
sales_b = [ 95, 108, 125, 140, 155, 168]
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(months, sales_a, marker="o", linewidth=2, color="#3b82f6", label="Product A")
ax.plot(months, sales_b, marker="s", linewidth=2, color="#f59e0b", label="Product B")
ax.set_title("Monthly Sales Comparison", fontsize=14, fontweight="bold")
ax.set_xlabel("Month")
ax.set_ylabel("Units Sold")
ax.legend()
ax.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()

4Bar and Horizontal Bar Charts

Bar charts compare values across categories. Vertical bars work for short labels; horizontal bars are better for long category names.

Vertical and Horizontal Bars

Add value labels to vertical bars, then build a horizontal version for long labels.

code
# Vertical bar chart
categories = ["Engineering", "Marketing", "Sales", "Support"]
headcount = [42, 18, 31, 15]
fig, ax = plt.subplots(figsize=(8, 5))
bars = ax.bar(categories, headcount, color=["#3b82f6", "#f59e0b", "#10b981", "#8b5cf6"])
ax.bar_label(bars, padding=3)  # add value labels on bars
ax.set_title("Headcount by Department")
ax.set_ylabel("Employees")
ax.set_ylim(0, 50)
plt.tight_layout()
# Horizontal bar (better for long category names)
fig, ax = plt.subplots(figsize=(10, 6))
y_pos = range(len(categories))
ax.barh(list(y_pos), headcount, color="#3b82f6")
ax.set_yticks(list(y_pos))
ax.set_yticklabels(categories)
ax.set_xlabel("Employees")
plt.tight_layout()

5Scatter Plots

Scatter plots reveal the relationship between two variables. Adding a fitted trend line makes the correlation easy to read.

Study Hours vs Test Score

Plot the points, fit a first-degree polynomial, and overlay the trend line.

code
# Scatter: relationship between two variables
np.random.seed(42)
study_hours = np.random.uniform(1, 10, 50)
test_scores = study_hours * 8 + np.random.normal(0, 10, 50)
fig, ax = plt.subplots(figsize=(8, 6))
ax.scatter(study_hours, test_scores, alpha=0.6, s=60, color="#3b82f6")
# Add trend line
z = np.polyfit(study_hours, test_scores, 1)
p = np.poly1d(z)
x_line = np.linspace(study_hours.min(), study_hours.max(), 100)
ax.plot(x_line, p(x_line), color="#ef4444", linewidth=2, linestyle="--", label="Trend")
ax.set_title("Study Hours vs Test Score")
ax.set_xlabel("Study Hours")
ax.set_ylabel("Test Score")
ax.legend()
plt.tight_layout()

6Histograms and Distributions

Histograms show the distribution of a single variable. Adding a vertical line at the mean gives an immediate reference point.

Distribution of Exam Scores

Bin 1,000 simulated scores and mark the mean with a dashed line.

code
# Histogram: distribution of a single variable
data = np.random.normal(60, 15, 1000)  # 1000 exam scores
fig, ax = plt.subplots(figsize=(8, 5))
ax.hist(data, bins=30, color="#3b82f6", edgecolor="white", alpha=0.8)
ax.axvline(data.mean(), color="#ef4444", linestyle="--", label=f"Mean: {data.mean():.1f}")
ax.set_title("Distribution of Exam Scores")
ax.set_xlabel("Score")
ax.set_ylabel("Frequency")
ax.legend()
plt.tight_layout()

7Multiple Subplots

A grid of subplots packs several related charts into one figure — ideal for dashboards. Index into the axes array to plot in each cell, then save the whole figure.

A 2x2 Dashboard Grid

Add a figure-level title, plot in each cell, and save the result to PNG.

code
# 2x2 grid of subplots
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
fig.suptitle("Sales Dashboard Q2 2026", fontsize=16, fontweight="bold")
# Plot in each cell
axes[0, 0].plot([1,2,3,4], [100,120,110,140])
axes[0, 0].set_title("Revenue Trend")
axes[0, 1].bar(["A","B","C"], [30, 45, 25])
axes[0, 1].set_title("Sales by Region")
axes[1, 0].hist(np.random.normal(50, 10, 200), bins=20)
axes[1, 0].set_title("Score Distribution")
axes[1, 1].scatter(range(20), np.random.rand(20) * 100, alpha=0.6)
axes[1, 1].set_title("Customer Value")
plt.tight_layout()
plt.savefig("dashboard.png", dpi=150, bbox_inches="tight")
plt.show()

8Styling and Themes

Built-in styles and global rcParams change the look of every chart in a session. Pick a style for a consistent baseline, then tweak defaults like DPI, font family, and spine visibility.

💡Pro Tip

Remove the top and right spines (ax.spines["top"].set_visible(False)) on every chart. This single change makes charts look immediately more professional. Pair with a light grey horizontal grid and white background for a clean, publication-ready style.

Styles and Global Defaults

Apply a style and set session-wide rcParams.

code
# Available styles
print(plt.style.available)
# Apply a style
plt.style.use("seaborn-v0_8-whitegrid")  # clean white grid
plt.style.use("ggplot")  # R-style
plt.style.use("dark_background")  # dark mode
# Set global defaults for all charts in the session
plt.rcParams["figure.dpi"] = 150
plt.rcParams["font.family"] = "sans-serif"
plt.rcParams["axes.spines.top"] = False
plt.rcParams["axes.spines.right"] = False  # remove box borders

9Seaborn: Statistical Visualisation

Seaborn produces beautiful statistical charts in a single line and integrates directly with matplotlib axes. It ships with built-in datasets and one-call plots for distributions, box plots, violins, regressions, and pair plots.

Three Python visualisation libraries for different use cases.
Three Python visualisation libraries for different use cases.

Seaborn Statistical Plots

Set the theme, load a dataset, and create several statistical plots.

code
import seaborn as sns
sns.set_theme(style="whitegrid")  # apply seaborn theme globally
# Load a built-in dataset
tips = sns.load_dataset("tips")
# Distribution plot with KDE
fig, ax = plt.subplots(figsize=(8, 5))
sns.histplot(tips["total_bill"], kde=True, ax=ax, color="#3b82f6")
ax.set_title("Distribution of Total Bills")
# Box plot: distribution across categories
fig, ax = plt.subplots(figsize=(8, 5))
sns.boxplot(data=tips, x="day", y="total_bill", ax=ax)
# Violin plot: richer distribution view
sns.violinplot(data=tips, x="sex", y="tip", hue="smoker")
# Regression plot: scatter + trend line in one call
sns.regplot(data=tips, x="total_bill", y="tip")
# Pair plot: all pairwise relationships in a dataset
sns.pairplot(tips, hue="sex")

10Heatmaps and Correlation Matrices

Correlation heatmaps are essential in data science for spotting relationships between features at a glance. Annotate the cells and centre the colour map at zero so positive and negative correlations read clearly.

Feature Correlation Matrix

Compute the correlation matrix and render it as an annotated heatmap.

code
# Correlation heatmap (essential for data science)
iris = sns.load_dataset("iris")
corr = iris.select_dtypes("number").corr()
fig, ax = plt.subplots(figsize=(7, 6))
sns.heatmap(
    corr,
    annot=True,  # show correlation values
    fmt=".2f",  # 2 decimal places
    cmap="coolwarm",  # blue=negative, red=positive
    center=0,  # 0 correlation = white
    square=True,
    ax=ax
)
ax.set_title("Feature Correlation Matrix")
plt.tight_layout()

11Saving Figures

Save figures in the format that fits the destination: PNG for web, SVG or PDF for print, or a bytes buffer for serving from a web framework. Always use bbox_inches="tight" to prevent labels from being clipped outside the figure boundary.

Export Formats

Write the figure to file formats or an in-memory buffer.

code
# Save as PNG (raster, for web)
fig.savefig("chart.png", dpi=150, bbox_inches="tight")
# Save as SVG (vector, for print or web)
fig.savefig("chart.svg", bbox_inches="tight")
# Save as PDF (vector, for documents)
fig.savefig("chart.pdf", bbox_inches="tight")
# Save to a bytes buffer (for serving via FastAPI or Streamlit)
import io
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight")
buf.seek(0)  # rewind before reading

12Key Takeaways

A few consistent habits produce clean, professional charts whether you reach for matplotlib or Seaborn.

  • Use fig, ax = plt.subplots() — always create axes explicitly.
  • Every chart needs a title, axis labels, and (when multiple series) a legend.
  • Remove top and right spines for a cleaner look; add a light horizontal grid.
  • Seaborn excels at statistical plots (distributions, regressions, pair plots) with minimal code.
  • Use heatmaps with annot=True for correlation matrices in EDA.

13What to Learn Next

Apply visualisation in real projects with these follow-up guides.

  • Build a Streamlit Dashboard — embed your matplotlib charts in an interactive web app.
  • Data Science Through Bollywood — apply every chart type in this guide to real film data.
  • Pandas for Beginners — DataFrames integrate directly with matplotlib and Seaborn.

14Frequently Asked Questions

What is the difference between plt.show() and plt.savefig()? plt.show() displays the figure in an interactive window (or inline in Jupyter). plt.savefig() writes it to a file. Call savefig() before show() — calling show() first clears the figure, producing a blank saved file.

When should I use Plotly instead of matplotlib? Plotly creates interactive charts (zoom, hover, click) that work in browsers and Streamlit. Use it for dashboards where users need to explore data interactively. Matplotlib is better for static publication-quality figures (PDF reports, academic papers, social media posts) where interactivity isn't needed.

Why does my chart look different in Jupyter vs a script? Jupyter uses inline rendering at a fixed DPI; scripts open a GUI window. Use %matplotlib inline in Jupyter for inline display, or %matplotlib widget for interactive. In scripts, plt.show() opens the window and plt.savefig() saves without opening.

How do I make charts accessible for colourblind readers? Use colourblind-safe palettes: Seaborn's colorblind palette or matplotlib's tab10. Avoid red-green combinations. Add patterns or markers to distinguish lines beyond colour alone. Use sns.set_palette("colorblind") as a global default.

📄

Get The Print Version

Download a PDF of this article for offline reading.

About the Publisher

SV

SkillVeris Team

Data Science Team

Our data team shares real-world analytics, ML, and SQL insights grounded in industry practice.

View all posts

Never miss an update

Get the latest tutorials and guides delivered to your inbox.

No spam. Unsubscribe anytime.

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse