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.
Matplotlib can be installed using pip.
pip install matplotlib
The most commonly used module is
matplotlib.pyplot.
import matplotlib.pyplot as plt
The alias plt is the standard convention
used when working with Matplotlib.
The basic idea is to provide data to Matplotlib, select an appropriate chart type, customize the chart, and display or save the visualization.
A line chart is useful for showing changes over time.
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()
Markers make individual data points easier to identify.
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()
You can customize a line using different styles, widths, and markers.
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()
Bar charts are useful for comparing categories.
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()
A horizontal bar chart is useful when category names are long.
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()
Pie charts can be used to show proportions of a whole.
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()
Scatter plots help identify relationships between two variables.
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()
Histograms show the distribution of numerical data.
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()
Grid lines make it easier to read and compare values on a chart.
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()
The annotate() function can be used to display
information near individual points.
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()
Legends help identify multiple datasets displayed on the same chart.
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()
Subplots allow multiple charts to be displayed in one figure.
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()
Use figsize to control the size of a chart.
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()
Charts can be saved as PNG, JPG, PDF, SVG, and other formats.
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()
savefig() before show()
when you want to save the generated figure.
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 |
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()
An HR department can visualize employee performance scores.
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()
A website team can visualize the number of visitors received each day.
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()
A product manager can compare sales across different products.
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()
Matplotlib can visualize temperature measurements collected from sensors.
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()
A personal finance application can visualize expenses by category.
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()
A financial application can plot historical price data to visualize movement over time.
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()
Schools and colleges can visualize student marks across subjects.
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()
A company can compare expenses across departments.
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()
Multiple datasets can be displayed on the same chart for comparison.
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()
Matplotlib is commonly used together with NumPy for numerical calculations and visualization.
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()
Pandas DataFrames can be visualized directly using 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()
A common business workflow is: load CSV data → analyze it → create a chart.
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()
An e-commerce company may need to analyze revenue, orders, and customers together.
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()
The following example combines multiple visualization techniques into a small business 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()
For larger applications, the object-oriented API can provide clearer control over figures and axes.
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()
| 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. |
| 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. |
| 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 |
- 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.
- Import Matplotlib using
import matplotlib.pyplot as plt. - Use
plt.plot()for line charts. - Use
plt.bar()for category comparisons. - Use
plt.scatter()for relationships between variables. - Use
plt.pie()for proportions. - Use
plt.hist()for distributions. - Use
plt.title()to describe the chart. - Use
plt.xlabel()andplt.ylabel()for axes. - Use
plt.legend()when multiple datasets are present. - Use
plt.grid()when grid lines improve readability. - Use
plt.show()to display the chart. - Use
plt.savefig()to save visualizations. - Use Pandas or NumPy together with Matplotlib for data analysis workflows.
- Use the object-oriented API for larger visualization applications.