Skip to main content
Matplotlib is the foundational plotting library for Python. It gives you fine-grained control over every element of a chart — axes, tick marks, labels, legends, grids, colors, and line styles — making it possible to produce publication-quality figures from a few lines of code. Before you use higher-level libraries like Seaborn, understanding Matplotlib builds the conceptual foundation you’ll need to customize any chart to your exact requirements.

Installation and Import

Two Interfaces

Matplotlib offers two ways to create charts: For single charts, use the state-based approach. Switch to the object-oriented approach when building subplot grids.

Your First Plot

Customizing a Plot

You can control titles, labels, limits, grids, legends, and tick marks with plt. commands:

Visualizing Numerical Data

Numerical (continuous) data is best explored using plots that reveal trends, distributions, or correlations.

Histograms — Distributions

Histograms group continuous values into “bins” to show frequency distribution.
Adjust the bins parameter to control granularity. Too few bins hides the shape of the distribution; too many makes it jagged. A starting point of 20–30 bins works well for most datasets.

Scatter Plots — Correlations

Scatter plots reveal relationships between two continuous variables.

Visualizing Categorical Data

Categorical data (discrete groups like departments or courses) is best represented with bar charts.

Vertical Bar Chart

Horizontal Bar Chart (barh)

Use barh when category names are long — it prevents the labels from overlapping on the x-axis.

Numerical vs. Categorical — Box Plots

A box plot (whisker plot) compares the distribution of a numerical variable across categories. It displays five statistics: minimum, Q1, median, Q3, and maximum, and highlights outliers.

Multi-Panel Layouts with Subplots

When you need multiple charts side by side, switch to the object-oriented interface with plt.subplots().
plt.tight_layout() automatically adjusts spacing between subplots so titles and axis labels don’t overlap. Always call it before plt.show() when working with subplot grids.

Chart Type Quick Reference