Data visualisation with Python
Practical, exam-focused notes on creating and choosing data visualisations in Python (Matplotlib, pandas, Seaborn, Bokeh, Plotly) with definitions, formulas for data-to-screen mapping, runnable examples, common mistakes and exam tips.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Data visualisation helps an engineer turn raw measurements or model outputs into visual patterns that are easy to understand and act on. In practice you will use Python visualisation to explore datasets, report results and build dashboards for debugging models, monitoring systems and convincing stakeholders.
Key ideas
Start from first principles and plain definitions; each bold word is defined the first time it appears.
- Visualisation: the process of converting data into images (plots, charts, graphics) so a human can detect patterns, trends and outliers quickly. Use this word when you mean the whole process (data → image).
- Chart: an instance of a visualisation that uses marks (points, lines, bars) on a coordinate system to show data values.
- Mark: the basic graphical element used to represent data (for example, a point, a line or a bar). Marks are placed in a visual space using encodings.
- Encoding: a rule that maps a data field to a visual property (for example, mapping a numeric column to vertical position or to color). An encoding is a function f: data → visual property.
- Scale: the mathematical mapping inside an encoding that converts data values into visual values (for example, a linear scale or a logarithmic scale). A linear scale maps data values x in [dmin, dmax] to visual coordinates v in [vmin, vmax] by an affine transform.
- Axis: a drawn reference line with ticks and labels that shows the relationship between visual coordinates and data values.
- Legend: a small area that explains encodings such as color, shape or size used in the chart.
- Glyph: a complex mark composed of several visual attributes (for example, a pie slice or a custom symbol showing multiple variables).
- DataFrame: in pandas, a 2-dimensional labeled table with rows and columns used to store tabular data; methods on a DataFrame produce plots when combined with plotting libraries.
- Matplotlib: the core 2D plotting library in Python; it draws figures, axes and basic marks.
- Seaborn: a statistical plotting library built on Matplotlib that adds high-level interfaces for common plot types and aesthetic styles.
- Plotly: an interactive plotting library (client-side) that produces web-ready interactive figures.
- Bokeh: a Python library for interactive web visualisations with a server option for streaming and linking plots.
Exact statement often required in exams (visual encoding law):
- The Data-to-Visual Mapping using a linear scale is an affine map: v = a·x + b where a and b are constants set so data endpoints map to visual endpoints. Assumption: data is numeric and dmax ≠ dmin.
What to draw in typical exam diagrams (describe exactly):
- Scatter plot to show correlation: draw a rectangular coordinate system, label horizontal axis 'x: variable1 (units)' and vertical axis 'y: variable2 (units)', place 8–12 points scattered, draw a thin line for the best-fit (annotate slope and intercept), include a legend saying 'points = samples; line = least-squares fit'.
- Histogram: draw x-axis with bin intervals labelled, y-axis as frequency, draw contiguous bars with heights matching frequencies, show a normal curve if asked, annotate bin width.
Derivation universities ask for (linear mapping):
- Suppose data range [dmin, dmax] maps to visual pixel range [vmin, vmax].
- Let v = a·x + b. Solve for a and b using boundary conditions: vmin = a·dmin + b and vmax = a·dmax + b.
- Subtract: vmax - vmin = a·(dmax - dmin) ⇒ a = (vmax - vmin)/(dmax - dmin).
- Substitute: b = vmin - a·dmin.
- So v = vmin + (x - dmin)·(vmax - vmin)/(dmax - dmin). Assumptions: dmax ≠ dmin, linear perceptual mapping appropriate.
Perceptual ranking (must verify in review): many courses mention that elementary perceptual tasks are ranked for accuracy: position > length > angle > area > color/hue, so prefer encodings by position when accuracy matters. This is an empirical claim from visualization research.
When to choose a plot (rules of thumb):
- Use line plot for ordered numeric x (time series).
- Use scatter plot for relationship between two quantitative variables.
- Use bar chart for categorical comparisons.
- Use histogram for distribution of a single numeric variable.
- Use heatmap for a matrix of values or correlation matrix.
Formulas
v = vmin + (x - dmin)·(vmax - vmin)/(dmax - dmin) — v: visual coordinate (pixels), x: data value, dmin/dmax: data min/max, vmin/vmax: visual space min/max. Applies when using a linear scale and dmax ≠ dmin.
v = vmin + (log(x) - log(dmin))·(vmax - vmin)/(log(dmax) - log(dmin)) — logarithmic scale transform; used when data spans orders of magnitude; requires x>0, dmin>0 and dmax>0. Any log base may be used because it cancels in the ratio.
y = m·x + c — equation of a straight (regression) line; m: slope (units y per unit x), c: intercept (units of y). Applies to linear least-squares fit under assumptions of linear relation and noise model used in regression.
Python syntax to remember (call/argument meanings):
import matplotlib.pyplot as plt — plt is the state-based API used to create figures and axes.
fig, ax = plt.subplots(figsize=(w,h)) — create a figure and axes; w,h in inches.
ax.plot(x, y, label='name', color='C0', linewidth=1.5) — draw a line on axis ax; x,y are sequences.
ax.scatter(x, y, c=color, s=size, marker='o') — draw scatter points; c: color or array for colormap, s: marker size in points^2.
df.plot(kind='bar', x='col1', y='col2', ax=ax) — pandas plotting wrapper using Matplotlib.
import seaborn as sns; sns.histplot(data=df, x='col') — Seaborn histogram; data is DataFrame, x is column name.
sns.regplot(x='col1', y='col2', data=df) — scatter with linear fit (by seaborn).
import plotly.express as px; fig = px.scatter(df, x='col1', y='col2', color='cat') — quick Plotly Express scatter; fig.show() renders in notebook.
from bokeh.plotting import figure; from bokeh.io import output_file, save; p = figure(); p.circle(x, y); output_file('plot.html'); save(p) — basic Bokeh save to an HTML file.
Each line above: symbols are names or arguments; units apply to figure size (inches) and marker size (points^2). Use linear scale formulas when you want equal spacing; use log formula for multiplicative relationships.
Worked examples
Example 1 — simple line plot with pandas + Matplotlib (complete program). This creates a DataFrame, plots a time series and saves the figure.
# save as example_line.py
import pandas as pd
import matplotlib.pyplot as plt
# create simple data
data = {'time_s': [0, 1, 2, 3, 4], 'temperature_C': [20.0, 21.5, 23.1, 22.8, 24.0]}
df = pd.DataFrame(data)
# plot
fig, ax = plt.subplots(figsize=(6,4))
ax.plot(df['time_s'], df['temperature_C'], marker='o', color='C1', label='temp')
ax.set_xlabel('time (s)')
ax.set_ylabel('temperature (°C)')
ax.set_title('Temperature vs Time')
ax.grid(True)
ax.legend()
fig.savefig('temperature_plot.png')
print('Saved temperature_plot.png')
Sample run (no stdin required). Exact output printed to console:
Saved temperature_plot.png
(Program produces file temperature_plot.png; open it to verify line and points.)
Example 2 — scatter with regression using Seaborn (complete program). This generates numeric data, plots scatter and regression, and prints regression equation from numpy.
# save as example_scatter.py
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from numpy.linalg import lstsq
# data: x in meters, y in new units
x = np.array([0.5, 1.0, 1.5, 2.0, 2.5])
y = np.array([1.4, 2.1, 2.8, 3.6, 4.0])
df = pd.DataFrame({'x_m': x, 'y_units': y})
# fit linear regression y = m*x + c using least squares
A = np.vstack([x, np.ones(len(x))]).T
m, c = lstsq(A, y, rcond=None)[0]
print(f'Regression line: y = {m:.3f} * x + {c:.3f}')
# plot
sns.set(style='whitegrid')
fig, ax = plt.subplots(figsize=(6,4))
sns.regplot(x='x_m', y='y_units', data=df, ax=ax, ci=None, scatter_kws={'s':50})
ax.set_xlabel('x (m)')
ax.set_ylabel('y (units)')
ax.set_title('Scatter with linear fit')
fig.savefig('scatter_reg.png')
print('Saved scatter_reg.png')
Sample output (console):
Regression line: y = 1.340 * x + 0.770 Saved scatter_reg.png
(Values checked: using the given points, regression coefficients computed by least squares produce the line printed.)
Example 3 — textual example (model answer) for an exam question: Q: Explain why a histogram bin width choice affects conclusions and show how to choose a bin width. A (model answer summary): Define histogram and bin width. The histogram approximates the probability density: frequency/bin_width ≈ density. Too-large bin width smooths features (underfits); too-small produces noise (overfits). A rule: Freedman–Diaconis bin width = 2·IQR·n^{-1/3} where IQR is interquartile range and n sample size. State assumptions: data are independent samples from continuous distribution. Conclude: compute IQR and n, plug into formula, round to an integer number of bins if preferred.
Common mistakes
- Choosing an encoding by color hue to show quantitative differences — hue is not perceptually ordered and is inaccurate for magnitude judgments.
- Not labeling axes, units or legend — exams deduct points for missing labels.
- Forgetting to handle NaN values in DataFrame before plotting (pandas may drop them silently).
- Using default colormaps that are not colourblind-safe (e.g., rainbow) when accuracy matters.
For your exam
Types of questions you will get:
- Definitions: e.g., define visualisation, mark, encoding, scale.
- Short notes: when to use scatter vs bar vs histogram; pros/cons of log scale.
- Derivations: derive linear mapping from data range to pixel range (show algebraic steps above).
- Numericals/programs: small code writing tasks using Matplotlib/Seaborn or calculate slope/intercept from given points.
- Diagrams: draw and label a scatter plot or histogram; annotate axes and legend.
What a full-marks answer includes:
- Clear definition of bold technical terms used.
- Correct formula(s) with units and assumptions.
- A labelled diagram when asked (axes, units, ticks, legend, title, and mark placement or bar heights).
- For programs: valid Python code using the correct library, printed output or saved file noted, and explanation of each step.
Quick check
- Give one reason to choose a log scale over a linear scale.
- Write the mapping formula that converts data x in [dmin, dmax] to visual coordinate v in [vmin, vmax].
- Which encoding should you prefer for the most accurate comparison of numeric values: color hue or position?
Answers: 1) When data span several orders of magnitude so multiplicative differences are important. 2) v = vmin + (x - dmin)·(vmax - vmin)/(dmax - dmin). 3) Position.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?