Definition
A table of 365 daily temperatures tells you almost nothing at a glance. Draw them as a line and you instantly see summer, monsoon and winter. Matplotlib is the Python library behind most of the charts data scientists make.
Matplotlib is Python's foundational plotting library, created by John D. Hunter and first released in 2003. A chart is a Figure, the whole image, containing one or more Axes, each an individual plot with its own x-axis, y-axis, title and data. You draw on an Axes with methods such as plot (line), bar, scatter and hist (histogram), then label it with set_title, set_xlabel, set_ylabel and legend, and save it with savefig. Libraries such as pandas plotting and seaborn are built on top of Matplotlib.
In simple words
Think of the Figure as a sheet of chart paper and each Axes as a box drawn on it. You choose what to draw in each box: a line for change over time, bars for comparing groups, dots for relationships, and a histogram for how values are spread.
Overview
- matplotlib, created by John Hunter in 2003, is Python's foundational plotting library.
- A Figure is the whole canvas; an Axes is one plot inside it with its own x and y axes.
- The object-oriented style, fig, ax = plt.subplots(), is clearer than calling plt functions directly.
- Every chart needs a title, axis labels with units, and a legend when there are several series.
- plt.subplots(2, 2) makes a grid of charts for comparison.
- savefig("chart.png", dpi=150) saves a chart for reports.
Why it matters
Charts reveal patterns, trends and errors that numbers hide, and they communicate findings to people who will never read your code. Matplotlib gives full control over every part of a chart, and its ideas carry over to every other plotting tool.
Key terms
- Figure and Axes
- The Figure is the whole image; each Axes is one plot inside it.
- Line chart
- Points joined in order, best for change over time.
- Bar chart
- Rectangles whose lengths compare values across categories.
- Scatter plot
- Dots showing the relationship between two numeric variables.
- Histogram
- Bars showing how many values fall in each range (bin).
- Subplots
- Several Axes arranged in a grid within one Figure.
Types
Each chart type answers a different kind of question. These are the core chart types in matplotlib and when each fits.
1. Line chart
Points joined by lines along an ordered x-axis, usually time.
- How it works: ax.plot(x, y) draws it; several calls add several lines; markers and line styles distinguish them.
- Example: Monthly rainfall in Mumbai over two years.
- When to use it: Use it to show trends and change over time. Avoid it for unordered categories, where lines suggest a trend that does not exist.
2. Bar chart
Rectangles whose lengths show values for separate categories.
- How it works: ax.bar(categories, values) draws vertical bars and ax.barh horizontal ones; bars should start at zero.
- Example: Average marks in five subjects, or sales per city.
- When to use it: Use it to compare quantities across categories; use horizontal bars for long labels. Sorting the bars by value makes comparisons much faster to read.
3. Histogram
Bars showing how many values fall into each range (bin) of one numeric variable.
- How it works: ax.hist(values, bins=20) counts values per bin; the shape reveals skew, peaks and outliers.
- Example: The distribution of exam marks for 500 students.
- When to use it: Use it to see the shape of a distribution; try a few bin counts.
4. Scatter plot
One dot per observation, placed by two numeric variables.
- How it works: ax.scatter(x, y, c=group, s=size) can also show a third and fourth variable through colour and size.
- Example: Hours studied against marks, coloured by section.
- When to use it: Use it to look for relationships, clusters and outliers between two variables. With thousands of points, make them smaller or partly transparent so that crowded areas show.
5. Pie chart
A circle divided into slices showing parts of a whole.
- How it works: ax.pie(shares, labels=names, autopct="%1.0f%%") draws it; values must add to a meaningful whole.
- Example: Share of household spending on food, rent, travel and savings.
- When to use it: Use it rarely, for two to five parts; a bar chart is usually easier to read accurately.
6. Box plot and image plot
A box plot summarises a distribution with its median, quartiles and outliers; imshow draws a 2-D array as an image or heat map.
- How it works: ax.boxplot([group1, group2]) compares groups side by side; ax.imshow(matrix, cmap="viridis") with a colour bar shows values as colours.
- Example: Box plots of delivery times per city; imshow of a confusion matrix or a handwritten digit.
- When to use it: Use box plots to compare spreads across groups and imshow for images and matrices.
Explained in detail
The basic recipe
Most Matplotlib code follows the same pattern. First import pyplot as plt. Then create a figure and axes with fig, ax = plt.subplots(), or fig, axes = plt.subplots(1, 2) for two side-by-side plots. Draw with ax.plot(x, y) or another method, add a title and axis labels that include units, add a legend if there is more than one series, and finally save with fig.savefig("chart.png", dpi=150) or display it. Using the axes object (ax) rather than calling plt functions directly keeps code clear when a figure has several panels. In the browser on this site, any open figure appears as an image under your code when it runs.
Choosing the right chart
| Question | Chart | Matplotlib method |
|---|---|---|
| How did something change over time? | Line chart | ax.plot(dates, values) |
| Which category is largest? | Bar chart (sorted) | ax.bar(names, values) or ax.barh(...) |
| Are two variables related? | Scatter plot | ax.scatter(x, y) |
| How are values distributed? | Histogram | ax.hist(values, bins=20) |
| How do groups' distributions compare? | Box plot | ax.boxplot([group1, group2]) |
Making charts honest and readable
Always label axes with what they measure and the units, such as "Rainfall (mm)". Start bar charts at zero, because bar length is read as quantity; a bar axis starting at 80 makes a 5 per cent difference look like a doubling. Line charts may start elsewhere when the change matters more than the level, but say so clearly. Use colour purposefully: one highlight colour for the point you want noticed and grey for the rest, and choose colour-blind-friendly palettes, since about 8 per cent of men have some form of colour-vision deficiency. Avoid 3D effects and pie charts with many slices, which distort comparisons. Keep fonts large enough to read on a phone, and remove clutter such as heavy gridlines and borders.
- fig.tight_layout() stops labels overlapping when a figure has several panels.
- pandas DataFrames have a .plot() method that calls Matplotlib for quick charts, such as df.plot(x="month", y="rain").
Matplotlib has two styles of use. The pyplot style, calling plt.plot and plt.title directly, is quick for a single chart. The object-oriented style, creating fig and ax and calling methods on ax, is clearer for anything with more than one panel and is what most experienced users write.
How it works
- Decide the question the chart must answer and pick the chart type.
- Create the figure and axes with plt.subplots().
- Draw the data with the right method.
- Add a title, axis labels with units and a legend if needed.
- Check honesty (bars from zero, clear scales) and save or display the figure.
In code
import matplotlib.pyplot as plt
import numpy as np
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
rain_mm = [2, 1, 1, 2, 18, 520, 840, 560, 340, 90, 15, 4] # example data for a coastal city
temp_c = [24, 25, 27, 29, 30, 29, 28, 28, 28, 29, 28, 26]
fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))
colours = ["#c0c0c0"] * 12
colours[rain_mm.index(max(rain_mm))] = "#1f77b4" # highlight the wettest month
axes[0].bar(months, rain_mm, color=colours)
axes[0].set_title("Most rain falls in July")
axes[0].set_ylabel("Rainfall (mm)")
axes[1].plot(months, temp_c, marker="o")
axes[1].set_title("Temperature dips in the monsoon")
axes[1].set_ylabel("Average temperature (°C)")
rng = np.random.default_rng(0)
daily_rain = rng.gamma(0.6, 25, 92) # 92 monsoon days
axes[2].hist(daily_rain, bins=15, color="#4c9a2a")
axes[2].set_title("Most monsoon days are light rain")
axes[2].set_xlabel("Daily rainfall (mm)")
axes[2].set_ylabel("Number of days")
fig.tight_layout()
print("Wettest month:", months[rain_mm.index(max(rain_mm))], f"({max(rain_mm)} mm)")
print("June-September share of yearly rain:", f"{sum(rain_mm[5:9]) / sum(rain_mm):.0%}")
print("Figures drawn:", len(plt.get_fignums()), "with", len(fig.axes), "panels")Output
Wettest month: Jul (840 mm) June-September share of yearly rain: 94% Figures drawn: 1 with 3 panels
Try it yourself
Match the question to the chart
Which chart answers each question best?
- How did monthly sales change over a year?
- Which state produces the most rice?
- Do students who study more score higher?
- How are exam marks spread across the cohort?
Honest or misleading?
Judge each chart choice.
Axis labels that include units
Grey bars with one highlighted in colour
A 3D pie chart with twelve slices
A bar chart whose axis starts at 95 to compare 96 and 99
Common mistakes
- Missing axis labels or units.
- Starting bar charts at a value other than zero.
- Using a pie or 3D chart where a bar chart would be clearer.
Check yourself
Summary
- Matplotlib draws Figures containing Axes; use plot, bar, scatter and hist for the main chart types.
- Match the chart to the question, and label titles, axes and units.
- Keep charts honest: bars from zero, purposeful colour, no 3D distortion.
Finished reading?
Sources: Matplotlib: user guide and tutorials · Claus O. Wilke, Fundamentals of Data Visualization