Matplotlib
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.
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.
Basic Line Plot
A line plot is used to show the relationship between two continuous variables or to show trend over time.
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.show()
• 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
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).
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()
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.
Plotting Multiple Lines
You can plot several lines on the same axes. Using label + legend() makes it easy to identify each line.
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()
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.
Scatter Plot
Scatter plots are useful when you want to show the relationship between two numerical variables. Each point represents one observation.
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()
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.
Bar Chart
Bar charts are ideal for comparing discrete categories (skills, products, months, etc.).
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()
Power BI has the highest score (90) and Excel has the lowest (65) in this example.
Histogram
A histogram shows the distribution of a continuous variable by grouping values into bins (intervals).
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()
bins=30 means the data is divided into 30 intervals.Because we used
np.random.randn() the shape is approximately a normal (bell) curve.
Pie Chart
A pie chart shows how a whole is divided into parts (percentages).
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()
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.
Basic Customization
You can control almost every visual aspect of a plot: color, marker, line style, title size, grid, etc.
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()
•
marker="o" → circle markers•
linestyle="--" → dashed line•
color="green" → line color•
linewidth=2 → thickness of the line•
plt.grid(True) → shows background grid
Colors and Styles
Matplotlib accepts colors in several formats:
color="blue"color="#2563EB"(hex code)color=(0.2, 0.4, 0.8)(RGB tuple)
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()
Popular styles:
"seaborn-v0_8", "ggplot", "bmh", "fivethirtyeight".
Creating Subplots
You can display multiple plots in one figure using subplots.
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()
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.
Saving a Figure
You can save any plot to a file instead of (or in addition to) displaying it.
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
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 →
