Data Visualization

Matplotlib

01 · What is Matplotlib? File · Matplotlib · 1 of 12

What is Matplotlib?

Matplotlib is Python's drawing board for data.

It is the most widely used library for creating static, animated, and interactive visualizations in Python.

Python
import matplotlib.pyplot as plt
import numpy as np
pyplot is the module we use most of the time. It provides a simple interface similar to MATLAB.
Almost every plot starts with these two import lines.
02 · Basic Line Plot File · Matplotlib · 2 of 12

Basic Line Plot

A line plot is used to show the relationship between two continuous variables or to show trend over time.

Python
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.show()
Graph
1 2 3 4 5 2 4 6 8 10
Straight increasing line (y = 2x)
What the graph shows:
• X values go from 1 to 5
• Y values go from 2 to 10
• Because y = 2 × x, the points form a perfect straight line
• plt.plot() draws the line connecting the points
• plt.show() displays the figure on the screen
03 · Figure & Axes File · Matplotlib · 3 of 12

Figure and Axes

In Matplotlib, a Figure is the overall window or page that everything is drawn on.
An Axes is the area where the data is plotted (the actual graph).

Python
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title("Simple Plot")
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
plt.show()
Graph
Simple Plot X Axis Y Axis
fig, ax = plt.subplots() creates a figure and one axes object.
Most customization (title, labels, limits) is done on the ax object.
This style is called the Object-Oriented interface and is preferred for more complex plots.
04 · Multiple Lines File · Matplotlib · 4 of 12

Plotting Multiple Lines

You can plot several lines on the same axes. Using label + legend() makes it easy to identify each line.

Python
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, label="sin(x)")
plt.plot(x, y2, label="cos(x)")
plt.legend()
plt.title("Sine and Cosine")
plt.show()
Graph
Sine and Cosine sin(x) cos(x)
label is used to name each line.
plt.legend() displays a box that shows which color belongs to which line.
This is the standard way to compare multiple series on one graph.
05 · Scatter Plot File · Matplotlib · 5 of 12

Scatter Plot

Scatter plots are useful when you want to show the relationship between two numerical variables. Each point represents one observation.

Python
x = np.random.rand(50)
y = np.random.rand(50)

plt.scatter(x, y, color="blue", alpha=0.7)
plt.title("Scatter Plot")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.show()
Graph
Scatter Plot X values Y values
alpha=0.7 makes the points slightly transparent so overlapping points are still visible.
Scatter plots are the first choice when exploring correlation between two numeric columns.
06 · Bar Chart File · Matplotlib · 6 of 12

Bar Chart

Bar charts are ideal for comparing discrete categories (skills, products, months, etc.).

Python
categories = ["Python", "SQL", "Power BI", "Excel"]
values = [85, 70, 90, 65]

plt.bar(categories, values, color="#2563EB")
plt.title("Student Scores")
plt.ylabel("Score")
plt.show()
Graph
Student Scores Python SQL Power BI Excel 85 70 90 65
The height of each bar represents the value for that category.
Power BI has the highest score (90) and Excel has the lowest (65) in this example.
07 · Histogram File · Matplotlib · 7 of 12

Histogram

A histogram shows the distribution of a continuous variable by grouping values into bins (intervals).

Python
data = np.random.randn(1000)

plt.hist(data, bins=30, color="skyblue", edgecolor="black")
plt.title("Histogram of Random Data")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
Graph
Histogram of Random Data Value Frequency
bins=30 means the data is divided into 30 intervals.
Because we used np.random.randn() the shape is approximately a normal (bell) curve.
08 · Pie Chart File · Matplotlib · 8 of 12

Pie Chart

A pie chart shows how a whole is divided into parts (percentages).

Python
labels = ["Python", "SQL", "Excel", "Power BI"]
sizes = [40, 25, 15, 20]

plt.pie(sizes, labels=labels, autopct="%1.1f%%", startangle=90)
plt.title("Skill Distribution")
plt.show()
Graph
Skill Distribution 40% 25% 15% 20%
autopct="%1.1f%%" shows the percentage on each slice with one decimal place.
startangle=90 rotates the starting point so the first slice begins at the top.
09 · Customization File · Matplotlib · 9 of 12

Basic Customization

You can control almost every visual aspect of a plot: color, marker, line style, title size, grid, etc.

Python
x = [1, 2, 3, 4, 5]
y = [10, 15, 13, 18, 16]

plt.plot(x, y, marker="o", linestyle="--", color="green", linewidth=2)
plt.title("Customized Line Plot", fontsize=14)
plt.xlabel("Days")
plt.ylabel("Sales")
plt.grid(True)
plt.show()
Graph
Customized Line Plot Days Sales
Common customization options:
• marker="o" → circle markers
• linestyle="--" → dashed line
• color="green" → line color
• linewidth=2 → thickness of the line
• plt.grid(True) → shows background grid
10 · Colors & Styles File · Matplotlib · 10 of 12

Colors and Styles

Matplotlib accepts colors in several formats:

  • color="blue"
  • color="#2563EB" (hex code)
  • color=(0.2, 0.4, 0.8) (RGB tuple)
Python
plt.style.use("seaborn-v0_8")   # or "ggplot", "bmh", etc.

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.title("Using a Style Sheet")
plt.show()
Style sheets quickly change the overall look of all plots (colors, fonts, grid, background).
Popular styles: "seaborn-v0_8", "ggplot", "bmh", "fivethirtyeight".
11 · Subplots File · Matplotlib · 11 of 12

Creating Subplots

You can display multiple plots in one figure using subplots.

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

axes[0].plot([1, 2, 3], [4, 5, 6])
axes[0].set_title("Line Plot")

axes[1].bar(["A", "B", "C"], [3, 7, 5])
axes[1].set_title("Bar Chart")

plt.tight_layout()
plt.show()
Graph
Line Plot Bar Chart
plt.subplots(1, 2) creates 1 row and 2 columns of axes.
figsize=(10, 4) controls the overall size of the figure.
plt.tight_layout() automatically adjusts spacing so titles and labels do not overlap.
12 · Saving Figures File · Matplotlib · 12 of 12

Saving a Figure

You can save any plot to a file instead of (or in addition to) displaying it.

Python
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("My Plot")
plt.savefig("my_plot.png", dpi=300, bbox_inches="tight")
plt.show()
dpi=300 creates a high-resolution image suitable for reports or presentations.
bbox_inches="tight" removes extra white space around the plot.
Supported formats: .png, .jpg, .pdf, .svg
Home Matplotlib

Matplotlib — Python's Drawing Board for Data

Learn how to create line plots, scatter plots, bar charts, histograms, pie charts and customize them.

Select any topic from the left sidebar to begin.


Start Learning →