By WebNest Studio Engineering Team
Python Tutorial
Data Visualisation with matplotlib
A good chart reveals in seconds what a table hides: trends, comparisons, distributions and relationships. matplotlib is Python's foundational plotting library; pandas' .plot() and the statistical library seaborn are built on top of it.
This lesson covers the figure-and-axes model, the essential chart types (line, bar, scatter, histogram, pie and box plots), labelling and styling, multiple charts in one figure, plotting straight from pandas, and saving charts to files. Install with pip install matplotlib.
Why it matters
A chart shows in a second what a table of numbers hides: a trend, an outlier, a difference between groups. Matplotlib is the base plotting library of Python, and pandas and seaborn draw their charts through it. Presenting findings clearly is a core part of any data role, and a misleading chart is worse than none.
Figures and Axes
A Figure is the whole image; an Axes is one chart inside it with its own x/y axes. The recommended style is fig, ax = plt.subplots() and then calling methods on ax: ax.plot, ax.bar, ax.set_title, ax.set_xlabel, ax.legend. plt.subplots(2, 2, figsize=(10, 8)) creates a grid of axes. Show the chart with plt.show() (a window, or inline in Jupyter) or save it with fig.savefig("chart.png", dpi=150, bbox_inches="tight").
Choosing a Chart
- Line (
plot) — change over time. - Bar (
bar/barh) — comparing categories. - Scatter (
scatter) — relationship between two numeric variables. - Histogram (
hist) — distribution of one numeric variable. - Box plot (
boxplot) — median, spread and outliers across groups. - Pie (
pie) — parts of a whole; use sparingly, bars are usually easier to read.
Clear Charts
Always give a title, axis labels with units, and a legend when there is more than one series. Start bar charts at zero, avoid 3-D effects, keep colours meaningful, and annotate the key number (ax.bar_label, ax.annotate). pandas can plot directly — df.plot(kind="bar", x="city", y="revenue", ax=ax) — and seaborn (pip install seaborn) adds attractive statistical charts such as sns.barplot, sns.histplot and sns.heatmap with one line each.
Examples
Line and bar charts with labels, legend and annotations
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
online = [120, 135, 150, 170, 165, 190]
store = [100, 98, 110, 105, 120, 118]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
ax1.plot(months, online, marker="o", label="Online")
ax1.plot(months, store, marker="s", linestyle="--", label="Store")
ax1.set_title("Monthly sales (thousand Rs)")
ax1.set_xlabel("Month")
ax1.set_ylabel("Sales")
ax1.legend()
ax1.grid(alpha=0.3)
totals = [o + s for o, s in zip(online, store)]
bars = ax2.bar(months, totals, color="tab:green")
ax2.bar_label(bars) # value on top of each bar
ax2.set_title("Total sales")
ax2.set_ylim(0, max(totals) * 1.15)
fig.tight_layout()
fig.savefig("sales.png", dpi=150)
# plt.show() # opens a window when run locally
print("saved sales.png with", len(fig.axes), "charts")
plt.close(fig)
saved sales.png with 2 charts
Scatter, histogram, box plot and pie in one figure
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(3)
hours = rng.uniform(1, 10, 60)
marks = 30 + 6 * hours + rng.normal(0, 6, 60)
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
axes[0, 0].scatter(hours, marks, alpha=0.7)
axes[0, 0].set(title="Study hours vs marks", xlabel="Hours", ylabel="Marks")
axes[0, 1].hist(marks, bins=10, edgecolor="white")
axes[0, 1].set(title="Distribution of marks", xlabel="Marks", ylabel="Students")
groups = [rng.normal(70, 8, 40), rng.normal(75, 5, 40), rng.normal(65, 12, 40)]
axes[1, 0].boxplot(groups, tick_labels=["Class A", "Class B", "Class C"])
axes[1, 0].set_title("Marks by class")
axes[1, 1].pie([45, 30, 25], labels=["Books", "Electronics", "Other"], autopct="%1.0f%%")
axes[1, 1].set_title("Revenue share")
fig.tight_layout()
fig.savefig("dashboard.png", dpi=120)
print("correlation:", np.corrcoef(hours, marks)[0, 1].round(2))
print("saved dashboard.png:", [ax.get_title() for ax in axes.flat])
plt.close(fig)
correlation: 0.93
saved dashboard.png: ['Study hours vs marks', 'Distribution of marks', 'Marks by class', 'Revenue share']
Plotting directly from pandas
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({
"city": ["Pune", "Mumbai", "Delhi", "Chennai"],
"online": [420, 610, 380, 290],
"store": [300, 450, 410, 260],
}).set_index("city")
fig, ax = plt.subplots(figsize=(7, 4))
df.plot(kind="bar", ax=ax, rot=0, title="Revenue by city and channel")
ax.set_ylabel("Revenue (thousand Rs)")
fig.tight_layout()
fig.savefig("channels.png")
print(df.sum(axis=1).sort_values(ascending=False).to_dict())
print("legend:", [text.get_text() for text in ax.get_legend().get_texts()])
plt.close(fig)
{'Mumbai': 1060, 'Delhi': 790, 'Pune': 720, 'Chennai': 550}
legend: ['online', 'store']
Common Mistakes
- Charts without a title, axis labels or units.
- Using a line chart for unordered categories, or a pie chart with many slices.
- Bar charts whose y-axis does not start at zero, exaggerating differences.
- Mixing the plt.* state-machine style and the ax.* object style in the same chart.
- Forgetting plt.close() when creating many figures in a loop, which uses more and more memory.
Exercise
Draw a bar chart of the sales figures, with a title and axis labels, and save it to memory as a PNG. To confirm the chart is set up correctly without looking at it, print the number of bars, the title and the label of the x-axis.
Expected output: 3, Sales by item, Item (one per line)
import io
import matplotlib
matplotlib.use("Agg") # draw without opening a window
import matplotlib.pyplot as plt
items = ["pen", "bag", "book"]
amounts = [120, 450, 300]
fig, ax = plt.subplots()
# TODO: draw the bars, keeping the object that ax.bar returns
# TODO: set the title "Sales by item", the x label "Item" and the y label "Amount"
# TODO: save the figure to an io.BytesIO buffer in PNG format
# TODO: print the number of bars, the title and the x label
Show hints
- The methods are
ax.bar,ax.set_title,ax.set_xlabelandax.set_ylabel. fig.savefig(buffer, format="png")writes the image. The values are read back withax.get_title()andax.get_xlabel().
Show solution
import io
import matplotlib
matplotlib.use("Agg") # draw without opening a window
import matplotlib.pyplot as plt
items = ["pen", "bag", "book"]
amounts = [120, 450, 300]
fig, ax = plt.subplots()
bars = ax.bar(items, amounts)
ax.set_title("Sales by item")
ax.set_xlabel("Item")
ax.set_ylabel("Amount")
buffer = io.BytesIO()
fig.savefig(buffer, format="png")
print(len(bars))
print(ax.get_title())
print(ax.get_xlabel())
Quick quiz
1. Which chart best shows how a value changes over time?
- A. Pie chart
- B. Scatter plot
- C. Histogram
- D. Line chart
Show answer
D. A line connects the points in order and makes the trend visible.
2. Which chart shows the distribution of one numeric variable?
- A. Histogram
- B. Line chart
- C. Pie chart
- D. Bar chart of categories
Show answer
A. It groups the values into ranges and shows how many fall in each.
3. In fig, ax = plt.subplots(), what is ax?
- A. The whole window
- B. One plotting area, with its own axes, title and data
- C. The data
- D. The colour scheme
Show answer
B. A figure can contain several axes, arranged in a grid.
Interview questions
What is the difference between a Figure and an Axes in Matplotlib?
Show answer
The Figure is the whole image or window. An Axes is a single plot inside it, with its own x and y axes, title, labels and plotted data. One figure can hold many axes, created with plt.subplots(rows, columns). Calling methods on the axes object, the object-oriented style, is clearer than the plt. functions when there is more than one plot.
How do you choose the right chart for your data?
Show answer
By the question being asked. A line chart for change over time; a bar chart for comparing categories; a histogram or box plot for the distribution of one variable; a scatter plot for the relationship between two numeric variables. Pie charts are suitable only for a few parts of one whole. Every chart needs a title, labelled axes with units, and an honest scale.
Key Points to Remember
- fig, ax = plt.subplots() then ax.plot/bar/scatter/hist/boxplot/pie.
- Pick the chart for the question: trend, comparison, relationship, distribution or share.
- Label everything; add legends and value labels where helpful.
- subplots creates grids; savefig writes PNG/SVG/PDF files.
- pandas .plot() and seaborn build on matplotlib for quick charts.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
These examples need a project environment on your computer, so they can be copied but not run here. Codelab runs Python, FastAPI backends with SQLite, plain Java 17 and HTML/CSS/JavaScript.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering