Menu

Data Visualization Using Matplotlib and Seaborn

Numerical summaries provide useful information about datasets, but they cannot always reveal how observations are distributed or how variables relate to one another.

Data visualisation represents information graphically to make distributions, trends, comparisons, and relationships easier to examine.

Data visualisation in data science is the process of representing numerical and categorical information through charts, plots, and graphical structures to support exploratory analysis and communication.

Python provides Matplotlib and Seaborn as two commonly used libraries for creating visualisations.

Matplotlib offers detailed control over graphical elements, while Seaborn provides convenient interfaces for statistical plots and works with Pandas DataFrames.

What Is Matplotlib in Python?

Matplotlib is a Python library used to create static, interactive, and animated visualisations.

Its pyplot interface provides functions for constructing plots, setting labels, and displaying figures.

Matplotlib supports:

  • Line charts
  • Bar charts
  • Histograms
  • Scatter plots
  • Box plots
  • Heatmaps
  • Multiple-axis figures

A chart generally consists of a figure containing one or more axes.

The figure represents the overall drawing area, while an axes object contains the plotted data and coordinate system.

How Do You Create a Line Chart Using Matplotlib?

Line charts are useful for examining how numerical values change across an ordered sequence, particularly time.

Consider monthly sales revenue.

Month Sales Revenue (₹)
January 12000
February 15000
March 14000
April 18000
May 22000

Python implementation:

import matplotlib.pyplot as pltmonths = ["Jan", "Feb", "Mar", "Apr", "May"]sales = [12000, 15000, 14000, 18000, 22000]plt.plot(months, sales, marker="o")plt.title("Monthly Sales Trend")plt.xlabel("Month")plt.ylabel("Sales Revenue (₹)")plt.show()

Code Explanation

  • plt.plot() creates the line chart.
  • marker="o" displays circular markers.
  • plt.title() adds the chart title.
  • plt.xlabel() labels the horizontal axis.
  • plt.ylabel() labels the vertical axis.
  • plt.show() displays the figure.

The chart shows that sales generally increased across the period, although March experienced a temporary decline.

When Should You Use a Line Chart?

Line charts are appropriate for:

  • Monthly revenue trends
  • Daily website traffic
  • Temperature measurements over time
  • Stock level changes
  • Model training loss across epochs

A line chart should generally be used when observations have a meaningful sequence.

How Do You Create a Bar Chart?

Bar charts compare numerical values across discrete categories.

Consider revenue generated by different product categories.

import matplotlib.pyplot as pltcategories = ["Electronics", "Clothing", "Home Decor"]revenue = [20000, 10500, 3000]plt.bar(categories, revenue)plt.title("Revenue by Product Category")plt.xlabel("Product Category")plt.ylabel("Revenue (₹)")plt.show()

The resulting chart compares revenue across the three categories.

Electronics has the highest total revenue in the example.

When Should You Use a Bar Chart?

Bar charts are useful for comparing:

  • Revenue across departments
  • Customer counts across cities
  • Sales across product categories
  • Error counts across systems
  • Survey responses across groups

For comparisons involving many categories, horizontal bars may improve readability.

What Is a Histogram?

A histogram displays the frequency distribution of a numerical variable.

It divides the numerical range into intervals called bins.

The height of each bar represents the count or frequency of observations within the corresponding interval.

Consider customer spending values.

import matplotlib.pyplot as pltspending = [    500, 700, 800, 1000, 1200,    1500, 1800, 2200, 2500, 8000]plt.hist(spending, bins=5)plt.title("Customer Spending Distribution")plt.xlabel("Spending (₹)")plt.ylabel("Frequency")plt.show()

The histogram helps identify where customer spending values are concentrated.

The ₹8,000 observation may contribute to a longer right tail.

What Is the Difference Between a Histogram and a Bar Chart?

Feature Histogram Bar Chart
Data Type Numerical Usually categorical
Main Purpose Show distribution Compare categories
Horizontal Axis Numerical intervals Categories
Bar Arrangement Usually adjacent Usually separated
Common Example Customer spending distribution Revenue by category

The number and width of histogram bins influence how the distribution appears.

Too few bins may hide detail, while too many bins may exaggerate random variation.

What Is a Scatter Plot?

A scatter plot displays paired observations from two numerical variables.

Each point represents one observation.

Scatter plots are commonly used to investigate relationships, identify clusters, and detect unusual observations.

Consider advertising expenditure and sales revenue.

import matplotlib.pyplot as pltadvertising = [1000, 2000, 3000, 4000, 5000]sales = [5000, 8000, 11000, 14000, 17000]plt.scatter(advertising, sales)plt.title("Advertising Spend vs Sales Revenue")plt.xlabel("Advertising Spend (₹)")plt.ylabel("Sales Revenue (₹)")plt.show()

The points follow an increasing pattern.

This suggests a positive association between advertising expenditure and sales revenue in the example.

However, a scatter plot cannot establish causality.

Other factors may influence sales, including seasonal demand and product availability.

What Is a Box Plot?

A box plot summarises the distribution of numerical values using quartiles and whiskers.

The central line typically represents the median.

The box extends from the first quartile to the third quartile.

Its width along the data axis represents the IQR.

Whiskers extend according to the selected plotting rule, and observations beyond them may be shown separately.

Creating a Box Plot

import matplotlib.pyplot as pltsales = [    1000, 1200, 1500, 1800, 2000,    2200, 2500, 3000, 3500, 12000]plt.boxplot(sales)plt.title("Sales Distribution")plt.ylabel("Sales Revenue (₹)")plt.show()

The chart can help identify potential outliers and examine the spread of observations.

When Are Box Plots Useful?

Box plots support comparisons involving:

  • Customer spending across regions
  • Employee salaries across departments
  • Delivery times across service providers
  • Product prices across categories
  • Model errors across datasets

A box plot provides a compact distribution summary but does not show every characteristic of the underlying distribution.

What Is Seaborn in Python?

Seaborn is a statistical data visualisation library built on Matplotlib.

It provides high-level functions that simplify the construction of several common statistical plots.

Seaborn integrates with Pandas DataFrames and supports grouping variables through parameters such as hue.

Common Seaborn functions include:

Function Purpose
sns.histplot() Displays distributions
sns.scatterplot() Examines numerical relationships
sns.boxplot() Compares distributions
sns.barplot() Displays aggregated numerical estimates
sns.lineplot() Displays trends and relationships
sns.heatmap() Displays matrix values
sns.pairplot() Shows pairwise variable relationships
sns.violinplot() Displays distribution shape

How Do You Create a Histogram Using Seaborn?

import seaborn as snsimport matplotlib.pyplot as pltspending = [    500, 700, 800, 1000, 1200,    1500, 1800, 2200, 2500, 8000]sns.histplot(    spending,    bins=5)plt.title("Customer Spending Distribution")plt.xlabel("Spending (₹)")plt.show()

Seaborn provides convenient statistical plotting options while retaining compatibility with Matplotlib.

A Kernel Density Estimate (KDE) can also be added for suitable numerical datasets.

sns.histplot(    spending,    bins=5,    kde=True)

A KDE provides a smoothed estimate of the distribution's density.

However, density estimates can be misleading for very small samples or highly discrete data.

How Do You Create Grouped Visualizations in Seaborn?

Consider a dataset containing product categories and transaction values.

import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdf = pd.DataFrame({    "category": [        "Electronics",        "Electronics",        "Clothing",        "Clothing",        "Home Decor"    ],    "revenue": [12000, 8000, 4500, 6000, 3000]})sns.boxplot(    data=df,    x="category",    y="revenue")plt.title("Revenue Distribution by Category")plt.show()

The chart compares transaction-value distributions across product categories.

This dataset is deliberately small, so the chart is primarily instructional.

Meaningful distribution analysis generally requires more representative observations.

What Is a Heatmap?

A heatmap represents numerical values using differences in colour intensity.

Heatmaps are commonly used for correlation matrices, grouped statistics, and performance tables.

For example, a correlation heatmap can display associations between numerical features.

import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdf = pd.DataFrame({    "advertising": [10, 20, 30, 40, 50],    "traffic": [100, 150, 200, 250, 300],    "revenue": [500, 700, 900, 1200, 1500]})correlation = df.corr()sns.heatmap(    correlation,    annot=True,    vmin=-1,    vmax=1,    cmap="coolwarm")plt.title("Correlation Matrix")plt.show()

Code Explanation

  • df.corr() calculates pairwise correlation coefficients.
  • sns.heatmap() displays the matrix.
  • annot=True shows numerical values inside cells.
  • vmin and vmax define the displayed colour scale.
  • cmap selects a colour palette.

The chart helps identify variables that exhibit strong positive or negative linear associations.

What Is a Pair Plot?

A pair plot displays pairwise relationships between several numerical variables.

It typically includes scatter plots for variable pairs and univariate distributions along the diagonal.

import seaborn as snsimport matplotlib.pyplot as pltsns.pairplot(df)plt.show()

Pair plots can help identify potential relationships before statistical modelling.

However, the number of plots increases rapidly as more variables are included.

For a dataset containing many columns, selecting a smaller subset of relevant numerical features can improve readability.

How Do You Choose the Right Visualization?

The analytical objective should determine which chart is appropriate.

Analytical Question Recommended Visualization
How has revenue changed over time? Line chart
Which category generates the most sales? Bar chart
How are transaction values distributed? Histogram
Are there unusual observations? Box plot
Are two numerical variables related? Scatter plot
How do numerical variables correlate? Correlation heatmap
How do distributions differ between groups? Box plot or violin plot
What relationships exist among several features? Pair plot

The chart should represent the underlying information accurately.

What Are Common Data Visualization Mistakes?

Misleading Axis Scales

Truncated axes can exaggerate differences between categories.

For bar charts that encode magnitude through bar length, a zero baseline is generally appropriate.

  1. Excessive Visual Elements

Too many labels, colours, or graphical effects can make charts difficult to interpret.

2. Incorrect Chart Selection

Using a line chart for unrelated categories may imply a continuous relationship that does not exist.

3. Ignoring Sample Size

A visually apparent pattern may result from a small number of observations.

4. Confusing Correlation With Causation

A scatter plot showing an association does not demonstrate that one variable caused changes in another.

5. Missing Labels

Charts should contain meaningful titles, axis labels, and measurement units where relevant.

How Is Data Visualization Used in Machine Learning?

Visualisation supports several stages of machine learning development.

Before Training: Histograms and box plots help identify unusual distributions and potential data quality issues.

During Feature Engineering: Scatter plots and grouped charts help examine relationships between candidate features and target variables.

During Training: Learning curves display changes in training and validation performance across iterations.

During Evaluation: Confusion matrices, residual plots, and prediction-error distributions help identify model weaknesses.

After Deployment: Monitoring dashboards track changes in model performance, input distributions, and operational metrics.


Data Science Tutorial for Beginners

VA

Vaishali Ardhana



Learn via Video Course

undefined Logo

0 hrs



Get in Touch For Details