Popular Searches
Popular Course Categories
Popular Courses

Creating Charts and Graphs Using Matplotlib and Seaborn

Creating Charts and Graphs Using Matplotlib and Seaborn

Python Data Analysis and Visualization

Creating Charts and Graphs Using Matplotlib and Seaborn in Python

Course: Python Training

Topic: Creating Charts and Graphs Using Matplotlib and Seaborn

Course Link: Python Training Course at JustAcademy

Demo Registration: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Data Visualization in Python

Data visualization is the process of representing information through charts, graphs, and other visual elements. It helps users understand patterns, compare values, identify trends, detect outliers, and communicate analytical findings clearly.

Python provides powerful visualization libraries, especially Matplotlib and Seaborn. Matplotlib offers detailed control over individual chart elements, while Seaborn provides a high-level interface for creating attractive statistical visualizations.

These libraries are commonly used in data analysis, machine learning, business intelligence, scientific computing, finance, research, and reporting.

Learning Objectives

  • Understand the purpose of data visualization.
  • Install and import Matplotlib and Seaborn.
  • Create line charts, bar charts, scatter plots, histograms, and pie charts.
  • Customize chart titles, axes, colors, labels, legends, and grids.
  • Create statistical visualizations using Seaborn.
  • Visualize distributions, relationships, and correlations.
  • Create multiple charts in a single figure.
  • Save charts as image files.
  • Choose suitable charts for different datasets.
  • Build a complete data visualization project.

2. What Is Matplotlib?

Matplotlib is a widely used Python library for creating static, animated, and interactive visualizations. Its pyplot interface provides convenient functions for creating common charts.

Matplotlib is especially useful when you need precise control over chart appearance, axes, annotations, layout, and export settings.

2.1 Main Features of Matplotlib

  • Supports line charts, bar charts, scatter plots, histograms, pie charts, and many other visualizations.
  • Allows customization of colors, line styles, markers, fonts, axes, and legends.
  • Supports multiple plots in one figure.
  • Can save charts in formats such as PNG, JPG, SVG, and PDF.
  • Integrates with NumPy and Pandas.
  • Supports basic animation and interactive chart workflows.

2.2 Installing Matplotlib

Install Matplotlib using pip:

pip install matplotlib

2.3 Importing Matplotlib

import matplotlib.pyplot as plt

The common alias plt makes plotting functions easier to use. For example, plt.plot() creates a line plot and plt.show() displays the figure in supported environments.


3. What Is Seaborn?

Seaborn is a statistical data visualization library built on top of Matplotlib. It provides a high-level interface for producing informative charts with attractive default styling.

Seaborn works especially well with Pandas DataFrames, making it convenient to visualize datasets using column names rather than manually extracting every series.

3.1 Main Features of Seaborn

  • Provides attractive default themes and color palettes.
  • Supports statistical charts for distributions and relationships.
  • Works naturally with Pandas DataFrames.
  • Offers heatmaps, box plots, violin plots, pair plots, and regression plots.
  • Supports grouping and color-based categories through parameters such as hue.
  • Uses Matplotlib for lower-level customization and figure management.

3.2 Installing Seaborn

pip install seaborn

3.3 Importing Seaborn

import seaborn as sns
import matplotlib.pyplot as plt

Seaborn and Matplotlib can be used together. Seaborn creates the statistical plot, while Matplotlib can add titles, labels, annotations, or other finishing touches.

3.4 Matplotlib vs. Seaborn

Feature Matplotlib Seaborn
Main purpose General-purpose plotting and customization Statistical visualization and high-level plotting
Customization Detailed control over chart elements High-level options with Matplotlib customization available
Default appearance Simple, flexible defaults Styled defaults and color palettes
Data input Lists, arrays, Pandas Series, and other supported inputs Often uses DataFrames with named columns
Statistical charts Can create them with suitable calculations and plotting functions Includes convenient statistical plotting functions
Typical charts Line, bar, scatter, histogram, pie Box, violin, heatmap, pair plot, regression plot
Best suited for Precise chart control and custom visualizations Exploratory data analysis and statistical patterns

4. Preparing Data for Visualization

Charts are only as reliable as the data behind them. Before plotting, inspect the dataset, verify data types, handle missing values, and decide which variables should be compared.

4.1 Importing Required Libraries

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

4.2 Creating a Sample Dataset

The following example creates a small sales dataset for use throughout these notes.

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    "Sales": [12000, 15000, 13500, 18000, 21000, 19500],
    "Profit": [2000, 2800, 2400, 3500, 4200, 3900],
    "Orders": [120, 145, 138, 170, 195, 185]
}

df = pd.DataFrame(data)

print(df.head())
print(df.info())
print(df.describe())

This dataset contains monthly sales, profit, and order counts. It can be used to explore trends, compare metrics, and create different types of charts.

4.3 Checking for Missing Values

print(df.isna().sum())

Missing values can cause gaps, exclusions, or unexpected chart results. Decide whether to correct, fill, or exclude missing observations based on the meaning of the data.

4.4 Selecting the Correct Variables

  • Use a time or sequence variable for the horizontal axis when showing a trend.
  • Use numeric values for measurements such as revenue, temperature, or profit.
  • Use categorical variables for group comparisons.
  • Use multiple numeric variables when examining relationships or correlations.

5. Understanding the Basic Structure of a Matplotlib Chart

Matplotlib organizes visualizations around a figure and one or more axes.

  • Figure: The overall drawing area containing the chart or charts.
  • Axes: The area where data is plotted, including its coordinate system.
  • Axis: The horizontal or vertical scale and its tick marks.
  • Title: Describes what the chart shows.
  • Labels: Explain the meaning and units of the axes.
  • Legend: Identifies plotted data series or categories.
  • Grid: Helps readers compare positions and values.

5.1 A Basic Chart

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr"]
sales = [12000, 15000, 13500, 18000]

plt.plot(months, sales)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()

This example creates a simple line chart with a title and axis labels.

5.2 Using the Object-Oriented Interface

For more complex visualizations, use plt.subplots() to create a figure and axes explicitly.

fig, ax = plt.subplots(figsize=(8, 5))

ax.plot(months, sales, marker="o")
ax.set_title("Monthly Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")

fig.tight_layout()
plt.show()

The object-oriented approach makes it easier to manage multiple charts and customize each set of axes independently.


6. Creating Line Charts Using Matplotlib

A line chart connects data points in sequence. It is useful for showing trends over time, changes across ordered categories, and the progression of measured values.

6.1 Basic Line Chart

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
sales = [12000, 15000, 13500, 18000, 21000, 19500]

plt.plot(months, sales)
plt.title("Monthly Sales Trend")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()

6.2 Customizing a Line Chart

plt.figure(figsize=(9, 5))

plt.plot(
    months,
    sales,
    color="blue",
    linestyle="-",
    linewidth=2,
    marker="o",
    markersize=6,
    label="Sales"
)

plt.title("Monthly Sales Trend")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid(True, alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()

Important parameters:

  • color: Sets the line color.
  • linestyle: Controls the line pattern.
  • linewidth: Sets line thickness.
  • marker: Displays a symbol at each data point.
  • label: Supplies the series name used by the legend.
  • figsize: Controls the figure dimensions in inches.

6.3 Plotting Multiple Lines

profit = [2000, 2800, 2400, 3500, 4200, 3900]
orders = [120, 145, 138, 170, 195, 185]

fig, ax = plt.subplots(figsize=(9, 5))

ax.plot(months, sales, marker="o", label="Sales")
ax.plot(months, profit, marker="s", label="Profit")

ax.set_title("Monthly Sales and Profit")
ax.set_xlabel("Month")
ax.set_ylabel("Amount")
ax.legend()
ax.grid(True, alpha=0.3)

fig.tight_layout()
plt.show()

When the plotted series have very different scales, such as revenue and order counts, consider separate charts or an appropriately designed secondary axis rather than making one series difficult to interpret.

When to Use a Line Chart

  • Monthly revenue or profit trends.
  • Daily website traffic.
  • Temperature changes over time.
  • Model accuracy across training epochs.

7. Creating Bar Charts Using Matplotlib

A bar chart compares values across categories. It is useful for comparing product sales, department budgets, student marks, or counts by category.

7.1 Vertical Bar Chart

products = ["Laptop", "Monitor", "Keyboard", "Mouse"]
revenue = [150000, 96000, 30000, 12000]

plt.figure(figsize=(8, 5))
plt.bar(products, revenue)

plt.title("Revenue by Product")
plt.xlabel("Product")
plt.ylabel("Revenue")
plt.tight_layout()
plt.show()

7.2 Customizing Bar Charts

fig, ax = plt.subplots(figsize=(8, 5))

bars = ax.bar(
    products,
    revenue,
    color="steelblue",
    edgecolor="black"
)

ax.set_title("Revenue by Product")
ax.set_xlabel("Product")
ax.set_ylabel("Revenue")
ax.bar_label(bars, fmt="%.0f", padding=3)

fig.tight_layout()
plt.show()

The bar_label() method adds value labels to bars in supported Matplotlib versions.

7.3 Horizontal Bar Chart

fig, ax = plt.subplots(figsize=(8, 5))

ax.barh(products, revenue)
ax.set_title("Revenue by Product")
ax.set_xlabel("Revenue")
ax.set_ylabel("Product")

fig.tight_layout()
plt.show()

Horizontal bars are useful when category names are long or when the categories are easier to read vertically.

7.4 Grouped Bar Chart

import numpy as np
import matplotlib.pyplot as plt

products = ["Laptop", "Monitor", "Keyboard"]
online_sales = [80000, 50000, 18000]
store_sales = [70000, 46000, 12000]

x = np.arange(len(products))
width = 0.35

fig, ax = plt.subplots(figsize=(9, 5))

ax.bar(x - width / 2, online_sales, width, label="Online")
ax.bar(x + width / 2, store_sales, width, label="Store")

ax.set_xticks(x)
ax.set_xticklabels(products)
ax.set_title("Online vs Store Revenue")
ax.set_xlabel("Product")
ax.set_ylabel("Revenue")
ax.legend()

fig.tight_layout()
plt.show()

A grouped bar chart places multiple series side by side within each category so that their values can be compared directly.


8. Creating Scatter Plots Using Matplotlib

A scatter plot displays the relationship between two numeric variables. Each point represents an observation. Scatter plots can reveal positive or negative associations, clusters, and possible outliers.

8.1 Basic Scatter Plot

advertising = [1000, 1500, 2000, 2500, 3000, 3500]
sales_values = [12000, 14500, 17000, 19000, 23000, 26000]

plt.figure(figsize=(8, 5))
plt.scatter(advertising, sales_values)

plt.title("Advertising Spend vs Sales")
plt.xlabel("Advertising Spend")
plt.ylabel("Sales")
plt.show()

8.2 Customizing a Scatter Plot

plt.figure(figsize=(8, 5))

plt.scatter(
    advertising,
    sales_values,
    color="darkorange",
    marker="o",
    s=90,
    alpha=0.7,
    edgecolors="black"
)

plt.title("Advertising Spend vs Sales")
plt.xlabel("Advertising Spend")
plt.ylabel("Sales")
plt.grid(True, alpha=0.25)
plt.tight_layout()
plt.show()

The s parameter controls marker size, and alpha controls transparency.

8.3 Interpreting Scatter Plots

  • Positive association: Higher values of one variable tend to occur with higher values of the other.
  • Negative association: Higher values of one variable tend to occur with lower values of the other.
  • No clear association: The points do not show an obvious directional pattern.
  • Clusters: Groups of observations may have similar characteristics.
  • Outliers: Some observations are far from the overall pattern.

A visible association does not by itself prove that one variable causes changes in another.


9. Creating Histograms Using Matplotlib

A histogram displays the distribution of a numeric variable by grouping observations into intervals called bins. It helps identify spread, concentration, skewness, and possible unusual values.

9.1 Basic Histogram

marks = [55, 62, 67, 70, 72, 75, 75, 78, 81, 84, 88, 92, 95]

plt.figure(figsize=(8, 5))
plt.hist(marks, bins=5, edgecolor="black")

plt.title("Distribution of Student Marks")
plt.xlabel("Marks")
plt.ylabel("Number of Students")
plt.show()

9.2 Customizing a Histogram

plt.figure(figsize=(8, 5))

plt.hist(
    marks,
    bins=8,
    color="skyblue",
    edgecolor="black",
    alpha=0.8
)

plt.title("Student Marks Distribution")
plt.xlabel("Marks")
plt.ylabel("Frequency")
plt.grid(axis="y", alpha=0.25)
plt.tight_layout()
plt.show()

The number and width of bins affect the shape of the displayed distribution. Too few bins can hide detail, while too many can make random variation look like meaningful structure.

When to Use a Histogram

  • Exam marks or assessment scores.
  • Customer ages.
  • Product delivery times.
  • Employee salaries.
  • Transaction values.

10. Creating Pie Charts Using Matplotlib

A pie chart represents the proportions of a whole. It is most effective when the dataset contains a small number of categories whose values add up to a meaningful total.

10.1 Basic Pie Chart

departments = ["IT", "HR", "Finance", "Marketing"]
employees = [40, 15, 20, 25]

plt.figure(figsize=(7, 7))

plt.pie(
    employees,
    labels=departments,
    autopct="%1.1f%%",
    startangle=90
)

plt.title("Employee Distribution by Department")
plt.axis("equal")
plt.show()

10.2 Highlighting a Slice

explode = (0.08, 0, 0, 0)

plt.figure(figsize=(7, 7))

plt.pie(
    employees,
    labels=departments,
    autopct="%1.1f%%",
    explode=explode,
    startangle=90
)

plt.title("Employee Distribution by Department")
plt.axis("equal")
plt.show()

The explode parameter separates selected slices slightly from the center.

Best practice: For many categories or values that are close together, a sorted bar chart is often easier to interpret than a pie chart.


11. Creating Box Plots Using Matplotlib

A box plot summarizes the distribution of numeric data using quartiles, a median, and whiskers. Depending on the plotting convention, individual points beyond the whiskers may be shown as potential outliers.

11.1 Basic Box Plot

salary = [32000, 35000, 38000, 40000, 42000, 45000, 48000, 52000, 90000]

plt.figure(figsize=(7, 5))
plt.boxplot(salary)

plt.title("Employee Salary Distribution")
plt.ylabel("Salary")
plt.show()

11.2 Comparing Groups

it_salary = [50000, 55000, 58000, 62000, 70000]
hr_salary = [40000, 42000, 45000, 48000, 52000]
finance_salary = [52000, 60000, 65000, 70000, 76000]

plt.figure(figsize=(8, 5))
plt.boxplot(
    [it_salary, hr_salary, finance_salary],
    tick_labels=["IT", "HR", "Finance"]
)

plt.title("Salary Distribution by Department")
plt.xlabel("Department")
plt.ylabel("Salary")
plt.show()

On older Matplotlib versions, the parameter for category labels may be named labels rather than tick_labels. Use the argument supported by your installed version.


12. Adding Titles, Labels, Legends, and Grid Lines

Chart customization improves readability and helps the audience understand what is being shown.

12.1 Titles and Axis Labels

fig, ax = plt.subplots(figsize=(8, 5))

ax.plot(months, sales, marker="o")
ax.set_title("Monthly Sales Performance")
ax.set_xlabel("Month")
ax.set_ylabel("Sales (INR)")

plt.show()

12.2 Adding a Legend

fig, ax = plt.subplots()

ax.plot(months, sales, label="Sales")
ax.plot(months, profit, label="Profit")

ax.legend()
plt.show()

Always assign labels to plotted series when a legend is required. A legend is especially useful when multiple lines or categories are displayed.

12.3 Adding Grid Lines

fig, ax = plt.subplots()

ax.plot(months, sales, marker="o")
ax.grid(True, linestyle="--", alpha=0.3)

plt.show()

12.4 Rotating Tick Labels

fig, ax = plt.subplots(figsize=(9, 5))

ax.bar(products, revenue)
ax.tick_params(axis="x", labelrotation=30)

fig.tight_layout()
plt.show()

Rotating labels can help prevent overlapping text, particularly when category names are long.

12.5 Setting Axis Limits

fig, ax = plt.subplots()

ax.plot(months, sales)
ax.set_ylim(0, 25000)

plt.show()

Choose axis limits that make the chart easy to understand without misleading readers. In particular, be careful when truncating the vertical axis of bar charts because bar lengths encode magnitude.


13. Creating Charts with Seaborn

Seaborn offers functions that simplify many statistical visualizations. Most plotting functions accept a DataFrame and the names of its columns.

13.1 Applying a Theme

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style="whitegrid")

sns.lineplot(data=df, x="Month", y="Sales", marker="o")
plt.title("Monthly Sales Using Seaborn")
plt.tight_layout()
plt.show()

sns.set_theme() configures Seaborn's visual defaults, including the axes style and color palette. It affects subsequent plots in the current session.

13.2 Common Seaborn Plot Functions

Function Purpose
sns.lineplot() Shows trends and relationships using lines.
sns.barplot() Shows an estimated numeric value for each category, with uncertainty intervals when configured.
sns.countplot() Displays counts of observations in categories.
sns.scatterplot() Shows relationships between two numeric variables.
sns.histplot() Displays a numeric distribution.
sns.boxplot() Summarizes distributions across categories.
sns.violinplot() Displays a distribution's shape across categories.
sns.heatmap() Displays values in a color-coded matrix.
sns.pairplot() Compares distributions and relationships across multiple variables.
sns.regplot() Displays a relationship with a fitted regression line.

14. Creating Line Charts with Seaborn

Seaborn's lineplot() is useful for showing trends, especially when the data contains groups or repeated observations.

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style="whitegrid")

sns.lineplot(
    data=df,
    x="Month",
    y="Sales",
    marker="o",
    label="Sales"
)

plt.title("Monthly Sales Trend")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.tight_layout()
plt.show()

14.1 Comparing Categories with Hue

sales_by_channel = pd.DataFrame({
    "Month": ["Jan", "Feb", "Mar", "Apr", "Jan", "Feb", "Mar", "Apr"],
    "Channel": ["Online", "Online", "Online", "Online",
                "Store", "Store", "Store", "Store"],
    "Sales": [12000, 15000, 17000, 19000,
              10000, 13000, 14500, 16000]
})

sns.lineplot(
    data=sales_by_channel,
    x="Month",
    y="Sales",
    hue="Channel",
    marker="o"
)

plt.title("Sales by Channel")
plt.tight_layout()
plt.show()

The hue parameter separates observations by category using different colors. When repeated observations exist for a category and x-value, Seaborn may aggregate them and show an uncertainty interval, depending on the function and version. If the dataset is already aggregated, the chart will generally be easier to interpret.


15. Creating Bar Charts with Seaborn

Seaborn's barplot() generally displays an estimate of a numeric variable for each category. By default, it commonly uses the mean and may show an uncertainty interval. It is not the same as a simple count of category occurrences.

15.1 Basic Bar Plot

products_df = pd.DataFrame({
    "Product": ["Laptop", "Monitor", "Keyboard", "Mouse"],
    "Revenue": [150000, 96000, 30000, 12000]
})

sns.barplot(
    data=products_df,
    x="Product",
    y="Revenue"
)

plt.title("Revenue by Product")
plt.tight_layout()
plt.show()

15.2 Changing the Estimator

sns.barplot(
    data=products_df,
    x="Product",
    y="Revenue",
    estimator="sum",
    errorbar=None
)

plt.title("Total Revenue by Product")
plt.tight_layout()
plt.show()

For current Seaborn versions, the estimator is generally supplied as a function such as sum, and errorbar=None disables uncertainty intervals. Parameter support can differ between versions. When data is already aggregated to one row per product, a Matplotlib bar chart is also a straightforward choice.

15.3 Counting Categories with Countplot

orders_df = pd.DataFrame({
    "PaymentMethod": [
        "Card", "Cash", "Card", "UPI", "UPI",
        "Card", "Cash", "UPI", "Card"
    ]
})

sns.countplot(
    data=orders_df,
    x="PaymentMethod"
)

plt.title("Orders by Payment Method")
plt.xlabel("Payment Method")
plt.ylabel("Order Count")
plt.tight_layout()
plt.show()

Use countplot() when you want to count how many records belong to each category.


16. Creating Histograms and Distribution Plots with Seaborn

Seaborn provides histplot() for displaying distributions and can optionally add a kernel density estimate (KDE) curve.

16.1 Basic Histogram

marks_df = pd.DataFrame({
    "Marks": [55, 62, 67, 70, 72, 75, 75, 78, 81, 84, 88, 92, 95]
})

sns.histplot(
    data=marks_df,
    x="Marks",
    bins=6
)

plt.title("Distribution of Student Marks")
plt.tight_layout()
plt.show()

16.2 Histogram with a KDE Curve

sns.histplot(
    data=marks_df,
    x="Marks",
    bins=6,
    kde=True
)

plt.title("Student Marks with Density Curve")
plt.tight_layout()
plt.show()

A KDE curve is a smoothed estimate of the distribution. Its shape depends on smoothing settings and should not be treated as a direct count of observations.

16.3 Comparing Distributions by Category

scores_df = pd.DataFrame({
    "Department": ["IT"] * 5 + ["HR"] * 5,
    "Score": [70, 75, 80, 85, 90, 60, 65, 70, 72, 78]
})

sns.histplot(
    data=scores_df,
    x="Score",
    hue="Department",
    bins=6,
    element="step",
    stat="density",
    common_norm=False
)

plt.title("Score Distributions by Department")
plt.tight_layout()
plt.show()

When comparing groups, choose a normalization method that supports the intended comparison. Density plots compare distribution shapes, while count plots show frequencies.


17. Creating Box Plots and Violin Plots with Seaborn

17.1 Box Plot

A Seaborn box plot makes it convenient to compare a numeric variable across categories.

salary_df = pd.DataFrame({
    "Department": ["IT", "IT", "IT", "HR", "HR", "HR",
                   "Finance", "Finance", "Finance"],
    "Salary": [55000, 62000, 70000, 42000, 48000, 52000,
               60000, 68000, 75000]
})

sns.boxplot(
    data=salary_df,
    x="Department",
    y="Salary"
)

plt.title("Salary Distribution by Department")
plt.tight_layout()
plt.show()

17.2 Violin Plot

A violin plot combines distribution information with a mirrored density shape. It can reveal differences in spread and concentration that may not be apparent from a box plot alone.

sns.violinplot(
    data=salary_df,
    x="Department",
    y="Salary",
    inner="quartile",
    cut=0
)

plt.title("Salary Distribution by Department")
plt.tight_layout()
plt.show()

The violin shape represents an estimated distribution rather than the exact number of records at each value. Small samples can produce unstable-looking shapes.

17.3 Box Plot vs. Violin Plot

Feature Box Plot Violin Plot
Main information Median, quartiles, spread, and potential outliers Distribution shape and density
Readability Compact and easy to compare Shows more distribution detail
Best use Comparing medians and variability Comparing distribution shapes
Limitation Does not show the full distribution shape Density estimates can be misleading with small datasets

18. Creating Scatter Plots and Regression Plots with Seaborn

18.1 Scatter Plot

marketing_df = pd.DataFrame({
    "Advertising": [1000, 1500, 2000, 2500, 3000, 3500],
    "Sales": [12000, 14500, 17000, 19000, 23000, 26000],
    "Channel": ["A", "A", "B", "B", "A", "B"]
})

sns.scatterplot(
    data=marketing_df,
    x="Advertising",
    y="Sales",
    hue="Channel",
    s=100
)

plt.title("Advertising Spend vs Sales")
plt.tight_layout()
plt.show()

18.2 Regression Plot

A regression plot adds a fitted trend line to show the general relationship between two numeric variables.

sns.regplot(
    data=marketing_df,
    x="Advertising",
    y="Sales",
    scatter_kws={"alpha": 0.7},
    line_kws={"color": "red"}
)

plt.title("Advertising Spend and Sales Relationship")
plt.tight_layout()
plt.show()

A fitted line summarizes an association under the chosen model. It does not prove that advertising spend causes the observed sales changes. Other factors may influence both variables.


19. Creating Heatmaps with Seaborn

A heatmap represents values in a matrix using colors. It is commonly used for correlation matrices, missing-value patterns, and tables of summarized measurements.

19.1 Creating a Correlation Matrix

numeric_df = pd.DataFrame({
    "Sales": [12000, 15000, 13500, 18000, 21000, 19500],
    "Profit": [2000, 2800, 2400, 3500, 4200, 3900],
    "Orders": [120, 145, 138, 170, 195, 185],
    "Returns": [4, 5, 3, 6, 7, 5]
})

correlation = numeric_df.corr(numeric_only=True)

print(correlation)

19.2 Visualizing the Correlation Matrix

plt.figure(figsize=(8, 6))

sns.heatmap(
    correlation,
    annot=True,
    cmap="coolwarm",
    fmt=".2f",
    vmin=-1,
    vmax=1,
    center=0
)

plt.title("Correlation Heatmap")
plt.tight_layout()
plt.show()

Correlation coefficients generally range from -1 to 1. Values near 1 indicate strong positive linear association, values near -1 indicate strong negative linear association, and values near 0 indicate little linear association.

Correlation does not establish causation, and a near-zero linear correlation does not rule out a nonlinear relationship.

19.3 Heatmap of a Summary Table

summary = pd.DataFrame({
    "Q1": [100, 120, 90],
    "Q2": [130, 115, 105],
    "Q3": [145, 140, 110]
}, index=["Product A", "Product B", "Product C"])

sns.heatmap(
    summary,
    annot=True,
    fmt=".0f",
    cmap="YlGnBu"
)

plt.title("Quarterly Product Performance")
plt.tight_layout()
plt.show()

20. Creating Pair Plots with Seaborn

A pair plot shows pairwise relationships between multiple numeric variables. The diagonal typically displays each variable's distribution, while the other panels show relationships between pairs of variables.

iris = sns.load_dataset("iris")

sns.pairplot(
    iris,
    hue="species",
    diag_kind="hist"
)

plt.show()

This example uses Seaborn's built-in Iris dataset. Loading built-in datasets may require access to the dataset source depending on the Seaborn version and local environment.

When to Use Pair Plots

  • Exploring relationships among multiple numeric features.
  • Identifying potential clusters in a dataset.
  • Comparing distributions across classes.
  • Preparing features for machine learning.

Pair plots can become slow and crowded when many columns are included. Select a small set of meaningful numeric variables for easier interpretation.


21. Creating Multiple Charts in a Single Figure

Subplots allow related visualizations to be displayed together. This makes it easier to compare trends, distributions, and relationships without opening separate figures.

21.1 Multiple Matplotlib Charts

fig, axes = plt.subplots(2, 2, figsize=(12, 9))

axes[0, 0].plot(months, sales, marker="o")
axes[0, 0].set_title("Monthly Sales")

axes[0, 1].bar(months, profit)
axes[0, 1].set_title("Monthly Profit")

axes[1, 0].scatter(orders, sales)
axes[1, 0].set_title("Orders vs Sales")
axes[1, 0].set_xlabel("Orders")
axes[1, 0].set_ylabel("Sales")

axes[1, 1].hist(sales, bins=5, edgecolor="black")
axes[1, 1].set_title("Sales Distribution")

fig.tight_layout()
plt.show()

21.2 Multiple Seaborn Charts

fig, axes = plt.subplots(1, 2, figsize=(12, 5))

sns.barplot(
    data=products_df,
    x="Product",
    y="Revenue",
    ax=axes[0]
)
axes[0].set_title("Revenue by Product")

sns.histplot(
    data=marks_df,
    x="Marks",
    bins=6,
    ax=axes[1]
)
axes[1].set_title("Marks Distribution")

fig.tight_layout()
plt.show()

The ax parameter tells Seaborn which axes should receive the chart. Use fig.tight_layout() to reduce overlapping titles and labels.


22. Saving Charts to Files

Charts can be saved for reports, websites, presentations, dashboards, and documentation.

22.1 Saving a Matplotlib Figure

fig, ax = plt.subplots(figsize=(8, 5))

ax.plot(months, sales, marker="o")
ax.set_title("Monthly Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")

fig.tight_layout()
fig.savefig("monthly_sales.png", dpi=300, bbox_inches="tight")
plt.show()

22.2 Common Export Formats

Format Common use
PNG Reports, presentations, and web images
JPG/JPEG Compact raster images where some image compression is acceptable
SVG Scalable vector graphics for supported web and design workflows
PDF Documents and print-ready reports

22.3 Saving a Seaborn Chart

fig, ax = plt.subplots(figsize=(8, 5))

sns.barplot(
    data=products_df,
    x="Product",
    y="Revenue",
    ax=ax
)

ax.set_title("Revenue by Product")
fig.tight_layout()
fig.savefig("product_revenue.png", dpi=300, bbox_inches="tight")
plt.show()

Seaborn plots are Matplotlib figures or axes, so Matplotlib's figure-saving methods can be used. Save the figure before closing it.


23. Choosing the Right Chart for the Data

Goal Recommended chart Example
Show change over time Line chart Monthly revenue
Compare categories Bar chart Sales by product
Compare two numeric variables Scatter plot Advertising spend vs sales
Understand a numeric distribution Histogram or KDE plot Customer ages
Compare distributions across groups Box plot or violin plot Salary by department
Show parts of a whole Pie chart or bar chart Department share
Visualize a correlation matrix Heatmap Relationships among numeric features
Explore many numeric variables Pair plot Machine learning feature exploration
Show frequency of categories Count plot Orders by payment method

Guidelines for Selecting a Chart

  • Identify the question before selecting a visualization.
  • Use line charts for meaningful ordered sequences, particularly time.
  • Use bar charts when readers need to compare discrete categories.
  • Use scatter plots to investigate relationships between numeric variables.
  • Use histograms to understand the shape of a numeric distribution.
  • Use box plots to compare medians and variability across groups.
  • Use heatmaps when a color-coded matrix helps reveal patterns.
  • Avoid unnecessary 3D effects and decorative elements that obscure the data.

24. Common Visualization Errors and Troubleshooting

Problem Possible cause Solution
Chart does not appear Display environment or missing show() Call plt.show() in a compatible environment.
Module not found Library is not installed in the active environment Install the package in the environment running Python.
Seaborn reports a missing column Incorrect column name or capitalization Check df.columns and use the exact column name.
Numeric chart values are treated as text Column contains strings or mixed values Clean the column and use pd.to_numeric().
Labels overlap Small figure or long category names Increase figure size, rotate labels, or use a horizontal bar chart.
Legend is missing Series labels were not assigned Set label on plotted series and call legend().
Heatmap fails with unsuitable data Non-numeric columns included in correlation calculations Select numeric columns or specify numeric-only behavior.
Chart shows unexpected averages Seaborn's bar plot aggregates repeated observations Check the aggregation method or use a chart of pre-aggregated data.
Saved image cuts off labels Figure margins are too small Use tight_layout() and bbox_inches="tight".
Too many points obscure each other Overplotting Use transparency, smaller markers, sampling, or an appropriate density visualization.

25. Data Visualization Best Practices

  • Keep charts focused: Every chart should answer a specific question.
  • Use descriptive titles: Explain the subject and, where useful, the time period.
  • Label axes clearly: Include units such as INR, percentage, hours, or counts.
  • Choose readable colors: Ensure sufficient contrast and consider color-vision accessibility.
  • Use legends carefully: Include them when multiple series or categories need explanation.
  • Avoid clutter: Remove unnecessary grid lines, labels, borders, and decorative effects.
  • Check the data: Validate missing values, unusual observations, and unexpected data types.
  • Use suitable scales: Avoid misleading axis ranges and make transformations clear.
  • Consider the audience: Technical charts may contain more detail than executive summaries.
  • Do not imply causation: Visual correlation alone does not establish cause and effect.
  • Keep comparisons fair: Use consistent scales when comparing similar charts.
  • Save at appropriate resolution: Use suitable dimensions and file formats for the final destination.

26. Complete Mini Project: Sales Performance Visualization Dashboard

Project Objective

Create a small visual analysis of sales performance using Pandas, Matplotlib, and Seaborn. The project will display monthly sales, profit, product revenue, and the relationship between orders and sales.

Step 1: Create the Dataset

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

sales_df = pd.DataFrame({
    "Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    "Sales": [12000, 15000, 13500, 18000, 21000, 19500],
    "Profit": [2000, 2800, 2400, 3500, 4200, 3900],
    "Orders": [120, 145, 138, 170, 195, 185]
})

product_df = pd.DataFrame({
    "Product": ["Laptop", "Monitor", "Keyboard", "Mouse"],
    "Revenue": [150000, 96000, 30000, 12000]
})

print(sales_df)
print(product_df)

Step 2: Set a Consistent Theme

sns.set_theme(style="whitegrid", palette="deep")

Step 3: Create a Four-Chart Dashboard

fig, axes = plt.subplots(2, 2, figsize=(14, 10))

# Chart 1: Monthly sales trend
sns.lineplot(
    data=sales_df,
    x="Month",
    y="Sales",
    marker="o",
    ax=axes[0, 0]
)
axes[0, 0].set_title("Monthly Sales Trend")
axes[0, 0].set_xlabel("Month")
axes[0, 0].set_ylabel("Sales (INR)")

# Chart 2: Monthly profit
sns.barplot(
    data=sales_df,
    x="Month",
    y="Profit",
    ax=axes[0, 1],
    errorbar=None
)
axes[0, 1].set_title("Monthly Profit")
axes[0, 1].set_xlabel("Month")
axes[0, 1].set_ylabel("Profit (INR)")

# Chart 3: Product revenue
sns.barplot(
    data=product_df,
    x="Product",
    y="Revenue",
    ax=axes[1, 0],
    errorbar=None
)
axes[1, 0].set_title("Revenue by Product")
axes[1, 0].set_xlabel("Product")
axes[1, 0].set_ylabel("Revenue (INR)")

# Chart 4: Orders compared with sales
sns.scatterplot(
    data=sales_df,
    x="Orders",
    y="Sales",
    s=90,
    ax=axes[1, 1]
)
axes[1, 1].set_title("Orders vs Sales")
axes[1, 1].set_xlabel("Orders")
axes[1, 1].set_ylabel("Sales (INR)")

fig.suptitle("Sales Performance Dashboard", fontsize=16)
fig.tight_layout()
fig.savefig(
    "sales_performance_dashboard.png",
    dpi=300,
    bbox_inches="tight"
)
plt.show()

Compatibility note: The errorbar=None parameter is supported by current Seaborn versions. If you are using an older version, consult its documentation for the equivalent option.

Step 4: Analyze the Results

  • Identify the month with the highest sales.
  • Identify the month with the highest profit.
  • Compare revenue across the listed products.
  • Examine whether higher order counts are associated with higher sales.
  • Explain at least one limitation of the dataset before drawing business conclusions.

Step 5: Extend the Project

  • Add a department or sales-channel category.
  • Create a heatmap for numeric variables.
  • Compare product performance using grouped bars.
  • Export the chart as both PNG and PDF.
  • Write a short business summary of the findings.

Expected Learning Outcomes

  • Load and organize data using Pandas.
  • Create charts with both Matplotlib and Seaborn.
  • Use multiple subplots to build a compact dashboard.
  • Save a chart for use in a report or presentation.
  • Explain visual patterns without overstating conclusions.

27. Practice Exercises

  1. Create a line chart showing daily temperatures over one week.
  2. Create a vertical bar chart comparing the revenue of five products.
  3. Create a horizontal bar chart showing the number of employees in each department.
  4. Use a scatter plot to examine the relationship between study hours and exam marks.
  5. Create a histogram showing the distribution of customer ages.
  6. Use a pie chart to display a small set of category proportions.
  7. Create a box plot comparing salaries across three departments.
  8. Create a violin plot to compare marks across different classes.
  9. Generate a correlation heatmap from a numeric dataset.
  10. Use a Seaborn count plot to compare the frequency of payment methods.
  11. Create a pair plot for selected numeric features in a dataset.
  12. Build a two-by-two subplot layout containing a line chart, bar chart, histogram, and scatter plot.
  13. Customize titles, labels, legends, and grids for each chart.
  14. Save your final visualization as a high-resolution PNG file.
  15. Write a short explanation describing the patterns and limitations of your charts.

28. Interview Questions and Answers

Q1. What is data visualization?

Answer: Data visualization represents data using visual elements such as charts and graphs so that patterns, trends, relationships, and comparisons are easier to understand.

Q2. What is Matplotlib?

Answer: Matplotlib is a Python plotting library that provides flexible tools for creating and customizing visualizations.

Q3. What is Seaborn?

Answer: Seaborn is a statistical visualization library built on Matplotlib that offers high-level plotting functions and attractive defaults.

Q4. What is the difference between Matplotlib and Seaborn?

Answer: Matplotlib provides detailed control over chart elements, while Seaborn simplifies many statistical plots and works conveniently with DataFrames. They can be used together.

Q5. How do you create a line chart in Matplotlib?

Answer: Use plt.plot(x, y) or an axes method such as ax.plot(x, y).

Q6. What is the purpose of plt.show()?

Answer: It displays the current figure in supported plotting environments.

Q7. How do you add a title and labels?

Answer: Use plt.title(), plt.xlabel(), and plt.ylabel(), or use the object-oriented methods ax.set_title(), ax.set_xlabel(), and ax.set_ylabel().

Q8. When should you use a scatter plot?

Answer: Use a scatter plot to investigate relationships between two numeric variables and identify patterns, clusters, or potential outliers.

Q9. What is the difference between a histogram and a bar chart?

Answer: A histogram groups numeric observations into intervals, while a bar chart compares values across discrete categories.

Q10. What is a box plot?

Answer: A box plot summarizes a distribution using its median, quartiles, whiskers, and potentially outlying observations.

Q11. What is a heatmap?

Answer: A heatmap displays a matrix of values using colors. It is often used for correlation matrices and summarized tables.

Q12. How do you create a correlation heatmap?

Answer: Calculate a numeric correlation matrix, then pass it to sns.heatmap(), often with annot=True to display values.

Q13. What does the hue parameter do in Seaborn?

Answer: It separates data into categories and uses different colors to distinguish those groups.

Q14. What is the purpose of sns.set_theme()?

Answer: It configures Seaborn's default visual styling, including themes and color palettes.

Q15. How can you display multiple charts in one figure?

Answer: Use plt.subplots() to create a figure and multiple axes, then draw each chart on its assigned axes.

Q16. How do you save a chart?

Answer: Use fig.savefig("chart.png", dpi=300, bbox_inches="tight") or plt.savefig() when working with the current figure.

Q17. What is the purpose of a legend?

Answer: A legend explains which visual element corresponds to each data series or category.

Q18. What is the difference between sns.barplot() and sns.countplot()?

Answer: barplot() generally displays an estimated numeric value for each category, while countplot() displays the number of observations in each category.

Q19. Does correlation prove causation?

Answer: No. Correlation indicates an association between variables but does not establish that one variable causes the other.

Q20. How can you improve a chart with overlapping labels?

Answer: Increase the figure size, rotate labels, shorten category names, use horizontal bars, or adjust the layout with tight_layout().


29. Quick Revision Checklist

  • Install Matplotlib with pip install matplotlib.
  • Install Seaborn with pip install seaborn.
  • Import plotting functions using import matplotlib.pyplot as plt.
  • Import Seaborn using import seaborn as sns.
  • Use plot() for line charts.
  • Use bar() and barh() for vertical and horizontal bars.
  • Use scatter() or sns.scatterplot() for relationships between numeric variables.
  • Use hist() or sns.histplot() to explore distributions.
  • Use sns.boxplot() and sns.violinplot() to compare distributions.
  • Use sns.heatmap() to visualize matrix values.
  • Use sns.pairplot() to explore multiple numeric variables.
  • Use plt.subplots() to build multi-chart figures.
  • Set clear titles, axis labels, legends, and suitable scales.
  • Use fig.savefig() to export visualizations.
  • Check data quality before interpreting chart patterns.

30. Conclusion

Matplotlib and Seaborn are essential tools for creating meaningful data visualizations in Python. Matplotlib offers detailed control over chart elements, while Seaborn simplifies statistical visualization and provides convenient functions for exploring DataFrame-based datasets.

By practicing line charts, bar charts, scatter plots, histograms, box plots, violin plots, heatmaps, and multi-chart layouts, you can turn raw data into visual insights. Good visualization also requires selecting an appropriate chart, checking data quality, labeling values clearly, and avoiding conclusions that the evidence does not support.

Continue learning with the Python Training Course at JustAcademy. You can register for a course demo or visit the JustAcademy official website for more learning resources.

whatsapp