Python Matplotlib

Learn how to create charts, graphs, visual reports, and real-time data visualizations in Python using Matplotlib.

What is Matplotlib?

Matplotlib is one of the most widely used Python libraries for creating data visualizations. It allows you to represent numerical data using charts, graphs, plots, and figures.

📊 Data Visualization

Convert numerical data into easy-to-understand visual charts and graphs.

📈 Business Analysis

Analyze sales, revenue, expenses, customers, performance, and trends.

📉 Trend Analysis

Identify increases, decreases, patterns, and changes over time.

📋 Reporting

Create visual reports that make business data easier to understand.

1. Installing Matplotlib

Matplotlib can be installed using pip.

Installation
pip install matplotlib
Result: Matplotlib will be installed in your Python environment.
2. Importing Matplotlib

The most commonly used module is matplotlib.pyplot.

Python Code
import matplotlib.pyplot as plt

The alias plt is the standard convention used when working with Matplotlib.

3. Matplotlib Visualization Flow
Input Data
→
Matplotlib
→
Chart / Graph
→
Business Insight

The basic idea is to provide data to Matplotlib, select an appropriate chart type, customize the chart, and display or save the visualization.

4. Basic Line Plot

A line chart is useful for showing changes over time.

Line Plot
import matplotlib.pyplot as plt


months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [120, 150, 180, 170, 220]

plt.plot(months, sales)

plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.show()
Output:
Monthly Sales 100 125 150 175 200 225 Jan Feb Mar Apr May Month Sales
5. Adding Markers

Markers make individual data points easier to identify.

Markers
import matplotlib.pyplot as plt


days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
orders = [25, 35, 30, 45, 50]

plt.plot(
days,
orders,
marker="o"
)

plt.title("Daily Orders")
plt.xlabel("Day")
plt.ylabel("Orders")

plt.show()
Output:
Daily Orders 20 25 30 35 40 45 Mon Tue Wed Thu Fri Day Orders
6. Line Style and Width

You can customize a line using different styles, widths, and markers.

Line Customization
import matplotlib.pyplot as plt


months = ["Jan", "Feb", "Mar", "Apr"]
revenue = [50000, 62000, 58000, 75000]

plt.plot(
months,
revenue,
marker="o",
linestyle="--",
linewidth=2
)

plt.title("Monthly Revenue")
plt.xlabel("Month")
plt.ylabel("Revenue")

plt.show()
Output:
Monthly Revenue 40K 47K 54K 61K 68K 75K Jan Feb Mar Apr Month Revenue
7. Bar Chart

Bar charts are useful for comparing categories.

Bar Chart
import matplotlib.pyplot as plt


products = ["Laptop", "Phone", "Tablet", "Monitor"]
sales = [120, 250, 100, 180]

plt.bar(products, sales)

plt.title("Product Sales")
plt.xlabel("Product")
plt.ylabel("Units Sold")

plt.show()
Output:
Product Sales 0 50 100 150 200 250 120 250 100 180 Laptop Phone Tablet Monitor Product Units Sold
8. Horizontal Bar Chart

A horizontal bar chart is useful when category names are long.

Horizontal Bar Chart
import matplotlib.pyplot as plt


departments = [
"Information Technology",
"Human Resources",
"Finance",
"Marketing"
]

employees = [45, 20, 25, 30]

plt.barh(departments, employees)

plt.title("Employees by Department")
plt.xlabel("Number of Employees")

plt.show()
Output:
Employees by Department 0 10 20 30 40 50 Information Technology Human Resources Finance Marketing 45 20 25 30 Number of Employees
9. Pie Chart

Pie charts can be used to show proportions of a whole.

Pie Chart
import matplotlib.pyplot as plt


categories = [
"Electronics",
"Clothing",
"Groceries",
"Books"
]

sales = [40, 25, 20, 15]

plt.pie(
sales,
labels=categories,
autopct="%1.1f%%"
)

plt.title("Sales Distribution")

plt.show()
Output:
Sales Distribution 40.0% 25.0% 20.0% 15.0% Electronics — 40.0% Clothing — 25.0% Groceries — 20.0% Books — 15.0%
10. Scatter Plot

Scatter plots help identify relationships between two variables.

Scatter Plot
import matplotlib.pyplot as plt


advertising = [10, 20, 30, 40, 50]
sales = [25, 40, 48, 65, 80]

plt.scatter(advertising, sales)

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

plt.show()
Output:
Advertising vs Sales 0 10 20 30 40 50 20 40 60 80 100 120 Advertising Spend Sales
Business Use: A company can use a scatter plot to examine whether advertising spending is associated with sales.
11. Histogram

Histograms show the distribution of numerical data.

Histogram
import matplotlib.pyplot as plt


ages = [
22, 25, 28, 30, 31,
35, 36, 38, 40, 42,
45, 47, 50, 52, 55
]

plt.hist(ages, bins=5)

plt.title("Employee Age Distribution")
plt.xlabel("Age")
plt.ylabel("Number of Employees")

plt.show()
Output:
Employee Age Distribution 0 1 2 3 4 20 27 34 41 48 55 Age Number of Employees
12. Adding Grid Lines

Grid lines make it easier to read and compare values on a chart.

Grid
import matplotlib.pyplot as plt


months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [100, 130, 125, 170, 200]

plt.plot(months, sales, marker="o")

plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.grid(True)

plt.show()
Output:
Monthly Sales 100 125 150 175 200 Jan Feb Mar Apr May Month Sales
13. Adding Labels to Data Points

The annotate() function can be used to display information near individual points.

Annotations
import matplotlib.pyplot as plt


months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 150, 130, 190]

plt.plot(months, sales, marker="o")

plt.annotate(
"Highest Sales",
xy=("Apr", 190),
xytext=("Mar", 175),
arrowprops={"arrowstyle": "->"}
)

plt.title("Monthly Sales")
plt.show()
Output:
Monthly Sales 100 125 150 175 200 Jan Feb Mar Apr Highest Sales Month Sales
14. Adding Legends

Legends help identify multiple datasets displayed on the same chart.

Legend
import matplotlib.pyplot as plt


months = ["Jan", "Feb", "Mar", "Apr"]

online_sales = [100, 130, 150, 180]
store_sales = [80, 110, 125, 140]

plt.plot(
months,
online_sales,
marker="o",
label="Online"
)

plt.plot(
months,
store_sales,
marker="o",
label="Store"
)

plt.title("Online vs Store Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.legend()

plt.show()
Output:
Online vs Store Sales 60 90 120 150 180 Jan Feb Mar Apr Legend Online Store Month Sales
15. Multiple Charts with Subplots

Subplots allow multiple charts to be displayed in one figure.

Subplots
import matplotlib.pyplot as plt


months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 130, 150, 180]
expenses = [70, 80, 95, 110]

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

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

axes[1].plot(months, expenses, marker="o")
axes[1].set_title("Expenses")

plt.tight_layout()
plt.show()
Output:
Sales 100 120 140 160 180 Jan Feb Mar Apr Expenses 60 80 100 120 140 Jan Feb Mar Apr Month
16. Figure Size

Use figsize to control the size of a chart.

Figure Size
import matplotlib.pyplot as plt


months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 150, 180, 210]

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

plt.plot(months, sales, marker="o")

plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.show()
Output:
Monthly Sales 100 125 150 175 200 Jan Feb Mar Apr Month Sales
17. Saving a Chart as an Image

Charts can be saved as PNG, JPG, PDF, SVG, and other formats.

Save Figure
import matplotlib.pyplot as plt


months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 150, 180, 210]

plt.plot(months, sales, marker="o")

plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.savefig("monthly_sales.png")

plt.show()
Output:
Monthly Sales 100 125 150 175 200 Jan Feb Mar Apr Month Sales
✓ Chart saved as: monthly_sales.png
Note: Call savefig() before show() when you want to save the generated figure.
18. Real-Time Example: Monthly Sales Analysis

Suppose a company wants to analyze monthly sales. Matplotlib can convert the sales data into a visual trend.

Month Sales
January 120000
February 145000
March 135000
April 175000
May 210000
Real-Time Business Example
import matplotlib.pyplot as plt


months = [
"January",
"February",
"March",
"April",
"May"
]

sales = [
120000,
145000,
135000,
175000,
210000
]

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

plt.plot(
months,
sales,
marker="o",
linewidth=2
)

plt.title("Monthly Sales Analysis")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.grid(True)
plt.tight_layout()

plt.show()
Output:
Monthly Sales Analysis 100K 120K 140K 160K 180K 200K January February March April May 120,000 145,000 135,000 175,000 210,000 Month Sales
Business Result: Management can visually identify the monthly sales trend and investigate periods where sales changed significantly.
19. Real-Time Example: Employee Performance

An HR department can visualize employee performance scores.

Employee Performance
import matplotlib.pyplot as plt


employees = [
"Amit",
"Priya",
"Rahul",
"Sneha",
"Vikas"
]

performance = [82, 91, 76, 88, 95]

plt.bar(employees, performance)

plt.title("Employee Performance")
plt.xlabel("Employee")
plt.ylabel("Performance Score")

plt.ylim(0, 100)

plt.show()
Output:
Employee Performance 0 20 40 60 80 100 82 91 76 88 95 Amit Priya Rahul Sneha Vikas Employee Performance Score
Business Result: HR can compare performance scores across employees and use the chart as part of a reporting dashboard.
20. Real-Time Example: Website Traffic

A website team can visualize the number of visitors received each day.

Website Traffic
import matplotlib.pyplot as plt


days = [
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
"Sun"
]

visitors = [
1200,
1500,
1800,
1700,
2200,
3000,
2800
]

plt.plot(
days,
visitors,
marker="o"
)

plt.title("Website Traffic")
plt.xlabel("Day")
plt.ylabel("Visitors")

plt.grid(True)

plt.show()
Output:
Website Traffic 1,000 1,500 2,000 2,500 3,000 3,500 Mon Tue Wed Thu Fri Sat Sun 1,200 1,500 1,800 1,700 2,200 3,000 2,800 Day Visitors
Business Result: The marketing team can identify high-traffic and low-traffic days.
21. Real-Time Example: Product Sales Comparison

A product manager can compare sales across different products.

Product Comparison
import matplotlib.pyplot as plt


products = [
"Laptop",
"Mobile",
"Tablet",
"Headphones",
"Monitor"
]

units_sold = [
150,
420,
180,
350,
220
]

plt.barh(products, units_sold)

plt.title("Product Sales Comparison")
plt.xlabel("Units Sold")
plt.ylabel("Product")

plt.show()
Output:
Product Sales Comparison 0 100 200 300 400 Laptop Mobile Tablet Headphones Monitor 150 420 180 350 220 Units Sold Product
22. Real-Time Example: Temperature Monitoring

Matplotlib can visualize temperature measurements collected from sensors.

Temperature Monitoring
import matplotlib.pyplot as plt


hours = [
"9 AM",
"10 AM",
"11 AM",
"12 PM",
"1 PM",
"2 PM",
"3 PM"
]

temperature = [
24,
25,
27,
29,
31,
32,
30
]

plt.plot(
hours,
temperature,
marker="o"
)

plt.title("Daily Temperature")
plt.xlabel("Time")
plt.ylabel("Temperature (°C)")

plt.grid(True)

plt.show()
Output:
Daily Temperature 22°C 24°C 26°C 28°C 30°C 32°C 9 AM 10 AM 11 AM 12 PM 1 PM 2 PM 3 PM 24°C 25°C 27°C 29°C 31°C 32°C 30°C Time Temperature (°C)
Real-Time Use: The same approach can be connected to sensor data, CSV files, APIs, or databases to visualize measurements.
23. Real-Time Example: Expense Analysis

A personal finance application can visualize expenses by category.

Expense Distribution (Python / Matplotlib)
import matplotlib.pyplot as plt

categories = [
    "Rent",
    "Food",
    "Travel",
    "Shopping",
    "Bills"
]

expenses = [
    25000,
    8000,
    5000,
    7000,
    4000
]

plt.pie(
    expenses,
    labels=categories,
    autopct="%1.1f%%"
)

plt.title("Monthly Expense Distribution")

plt.show()
Output / Result Preview
24. Real-Time Example: Stock Price Trend

A financial application can plot historical price data to visualize movement over time.

Stock Price Visualization
import matplotlib.pyplot as plt

dates = [
    "Mon",
    "Tue",
    "Wed",
    "Thu",
    "Fri"
]

prices = [
    120,
    125,
    122,
    130,
    135
]

plt.plot(
    dates,
    prices,
    marker="o"
)

plt.title("Stock Price Trend")
plt.xlabel("Day")
plt.ylabel("Price")

plt.grid(True)

plt.show()
Output / Result Preview
Important: A chart shows historical or supplied data. It does not by itself predict future prices.
25. Real-Time Example: Student Marks Analysis

Schools and colleges can visualize student marks across subjects.

Student Marks
import matplotlib.pyplot as plt

subjects = [
    "Python",
    "Java",
    "SQL",
    "Math",
    "English"
]

marks = [
    88,
    82,
    91,
    76,
    85
]

plt.bar(subjects, marks)

plt.title("Student Marks")
plt.xlabel("Subject")
plt.ylabel("Marks")

plt.ylim(0, 100)

plt.show()
Output / Result Preview
26. Real-Time Example: Department Expenses

A company can compare expenses across departments.

Department Expense Analysis
import matplotlib.pyplot as plt

departments = [
    "IT",
    "HR",
    "Finance",
    "Marketing",
    "Operations"
]

expenses = [
    450000,
    180000,
    250000,
    320000,
    500000
]

plt.bar(
    departments,
    expenses
)

plt.title("Department Expenses")
plt.xlabel("Department")
plt.ylabel("Expense")

plt.show()
Output / Result Preview
27. Real-Time Example: Sales vs Expenses

Multiple datasets can be displayed on the same chart for comparison.

Sales vs Expenses
import matplotlib.pyplot as plt

months = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May"
]

sales = [
    120000,
    150000,
    180000,
    170000,
    220000
]

expenses = [
    80000,
    90000,
    110000,
    100000,
    125000
]

plt.plot(
    months,
    sales,
    marker="o",
    label="Sales"
)

plt.plot(
    months,
    expenses,
    marker="o",
    label="Expenses"
)

plt.title("Sales vs Expenses")
plt.xlabel("Month")
plt.ylabel("Amount")

plt.legend()
plt.grid(True)

plt.show()
Output / Result Preview
Business Use: Comparing multiple series can make financial trends easier to inspect in a single visualization.
28. Working with NumPy and Matplotlib

Matplotlib is commonly used together with NumPy for numerical calculations and visualization.

NumPy + Matplotlib
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10, 0.5)
y = x ** 2

plt.plot(x, y)

plt.title("Square Function")
plt.xlabel("X")
plt.ylabel("X²")

plt.grid(True)

plt.show()
Output / Result Preview
29. Working with Pandas and Matplotlib

Pandas DataFrames can be visualized directly using Matplotlib.

Pandas + Matplotlib
import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Month": ["Jan", "Feb", "Mar", "Apr"],
    "Sales": [100, 140, 170, 210]
}

df = pd.DataFrame(data)

plt.plot(
    df["Month"],
    df["Sales"],
    marker="o"
)

plt.title("Sales from DataFrame")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.show()
Output / Result Preview
Real-Time Use: This pattern is useful when data is loaded from CSV or Excel files using Pandas and then visualized.
30. Real-Time Example: CSV Sales Visualization

A common business workflow is: load CSV data → analyze it → create a chart.

CSV + Pandas + Matplotlib
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("sales.csv")

plt.plot(
    df["Month"],
    df["Sales"],
    marker="o"
)

plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.grid(True)

plt.show()
Output / Result Preview (Simulated CSV Data)
Workflow: CSV file → Pandas DataFrame → Matplotlib chart.
31. Real-Time Example: E-Commerce Dashboard

An e-commerce company may need to analyze revenue, orders, and customers together.

E-Commerce Analysis
import matplotlib.pyplot as plt

months = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun"
]

orders = [
    450,
    520,
    610,
    580,
    720,
    850
]

revenue = [
    180000,
    210000,
    250000,
    240000,
    310000,
    380000
]

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

axes[0].plot(
    months,
    orders,
    marker="o"
)

axes[0].set_title("Monthly Orders")
axes[0].set_xlabel("Month")
axes[0].set_ylabel("Orders")

axes[1].plot(
    months,
    revenue,
    marker="o"
)

axes[1].set_title("Monthly Revenue")
axes[1].set_xlabel("Month")
axes[1].set_ylabel("Revenue")

plt.tight_layout()
plt.show()
Output / Result Preview (Dashboard Subplots)
Business Result: Two related business metrics can be viewed together for easier reporting and analysis.
32. Real-Time Example: Complete Sales Report

The following example combines multiple visualization techniques into a small business sales report.

Complete Sales Report
import matplotlib.pyplot as plt

months = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun"
]

sales = [
    120000,
    145000,
    160000,
    150000,
    190000,
    220000
]

expenses = [
    80000,
    90000,
    100000,
    95000,
    115000,
    130000
]

profit = [
    sales[i] - expenses[i]
    for i in range(len(sales))
]

fig, axes = plt.subplots(3, 1, figsize=(10, 12))

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

axes[0].set_title("Sales Trend")
axes[0].set_ylabel("Sales")

axes[1].plot(
    months,
    expenses,
    marker="o"
)

axes[1].set_title("Expense Trend")
axes[1].set_ylabel("Expenses")

axes[2].bar(
    months,
    profit
)

axes[2].set_title("Monthly Profit")
axes[2].set_xlabel("Month")
axes[2].set_ylabel("Profit")

plt.tight_layout()
plt.show()
Output / Result Preview (Complete Report Subplots)
Result: The report displays sales, expenses, and calculated profit in a single figure.
33. Matplotlib Object-Oriented Approach

For larger applications, the object-oriented API can provide clearer control over figures and axes.

Object-Oriented Plot
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 140, 170, 210]

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

ax.plot(
    months,
    sales,
    marker="o"
)

ax.set_title("Monthly Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")

ax.grid(True)

plt.show()
Output / Result Preview
34. Matplotlib Figure and Axes
Object Purpose
Figure The overall drawing area.
Axes The area where a specific plot is drawn.
Axis Represents x-axis or y-axis scales.
Title Describes the chart.
Legend Identifies plotted datasets.
35. Common Matplotlib Functions
Function Purpose
plt.plot() Create a line plot.
plt.bar() Create a vertical bar chart.
plt.barh() Create a horizontal bar chart.
plt.scatter() Create a scatter plot.
plt.pie() Create a pie chart.
plt.hist() Create a histogram.
plt.title() Add a chart title.
plt.xlabel() Label the x-axis.
plt.ylabel() Label the y-axis.
plt.legend() Display the legend.
plt.grid() Display grid lines.
plt.show() Display the figure.
plt.savefig() Save the figure to a file.
plt.subplots() Create a figure and axes.
36. Choosing the Right Chart
Requirement Recommended Chart
Show a trend over time Line chart
Compare categories Bar chart
Compare long category names Horizontal bar chart
Show proportions Pie chart
Show relationship between variables Scatter plot
Show numerical distribution Histogram
Compare multiple metrics Subplots
37. Matplotlib Best Practices
  • Always give charts meaningful titles.
  • Use clear x-axis and y-axis labels.
  • Choose chart types based on the data.
  • Avoid unnecessary visual clutter.
  • Use legends when multiple datasets are displayed.
  • Use tight_layout() when needed.
  • Save important charts using savefig().
  • Use readable labels and appropriate figure sizes.
  • Keep units clear when displaying financial or scientific data.
  • Validate the source data before creating visualizations.
38. Important Matplotlib Rules
  1. Import Matplotlib using import matplotlib.pyplot as plt.
  2. Use plt.plot() for line charts.
  3. Use plt.bar() for category comparisons.
  4. Use plt.scatter() for relationships between variables.
  5. Use plt.pie() for proportions.
  6. Use plt.hist() for distributions.
  7. Use plt.title() to describe the chart.
  8. Use plt.xlabel() and plt.ylabel() for axes.
  9. Use plt.legend() when multiple datasets are present.
  10. Use plt.grid() when grid lines improve readability.
  11. Use plt.show() to display the chart.
  12. Use plt.savefig() to save visualizations.
  13. Use Pandas or NumPy together with Matplotlib for data analysis workflows.
  14. Use the object-oriented API for larger visualization applications.
Python Matplotlib

Create meaningful visualizations and turn data into useful insights.