Knowledge / Artificial Intelligence and Data Science / Data visualisation

Data visualisation

Artificial Intelligence and Data Science (B.E./B.Tech) · Programming and data · free study notes for exams, placements and interviews

In short

Data visualisation is the practice of mapping numbers and categories to visual properties - position, length, angle, area, colour, shape - so that patterns, comparisons and outliers become visible far faster than from a table. For an AI and Data Science student it sits in the middle of the workflow: exploratory data analysis (EDA) before modelling, diagnostics during modelling, and reporting after it. It is examined in Python/data-analytics laboratory courses, in "Data Visualisation" or "Exploratory Data Analysis" papers under AICTE and CBCS curricula, and in GATE DA through questions on chart choice, reading distributions and interpreting correlation plots. Indian employers - TCS, Infosys, Wipro, Accenture, Deloitte, EXL, Mu Sigma, Fractal, Zomato, Flipkart, PhonePe, banks and the analytics cells of government departments - test matplotlib/seaborn fluency plus Power BI or Tableau in almost every data-analyst interview. Marks and offers are lost less on syntax than on choosing the wrong chart and misreading a scale.

Explained

Why visualise: perception and the grammar of graphics

Data types decide the chart

Matplotlib, seaborn, plotly - the Python stack

BI tools and dashboards

Doing it right: scales, colour, annotation, accessibility, ethics

Reading and interpreting charts (the exam skill)

Key points

Formulas and examples

Data-ink ratio = (ink used to display data) ÷ (total ink used in the graphic). Dimensionless, 0 to 1; higher is better.
Lie factor = (size of effect shown in graphic) ÷ (size of effect in data). Dimensionless; 1 = honest, >1 exaggerates.
Sturges' rule: k = 1 + log₂(n) bins; bin width h = (max − min)/k. n = number of observations, k rounded to an integer.
Freedman–Diaconis rule: h = 2 × IQR × n−1/3; k = ceil((max − min)/h). Robust to outliers; h in the data's own units.
Five-number summary / box plot: lower fence = Q1 − 1.5 × IQR, upper fence = Q3 + 1.5 × IQR, IQR = Q3 − Q1. Points outside the fences are plotted as outliers.
Pearson correlation (heatmaps): r = Σ(xᵢ − x̄)(yᵢ − ȳ) / √[Σ(xᵢ − x̄)² Σ(yᵢ − ȳ)²], −1 ≤ r ≤ +1, dimensionless.
Pie chart angle: θᵢ = 360° × (valueᵢ / Σ values); percentage = 100 × valueᵢ / Σ values.
Min–max scaling for bubble/colour: x′ = (x − min)/(max − min) ∈ [0,1]; for area-true bubbles, radius ∝ √value.
Aspect ratio of a saved figure = figsize_width × dpi : figsize_height × dpi pixels, e.g. (8,6) at 300 dpi = 2400 × 1800 px.

Example 1 - Bin count for a histogram of salaries. A placement cell has n = 1,000 CTC values, min = ₹2.4 lakh, max = ₹18.0 lakh, Q1 = ₹3.6 lakh, Q3 = ₹7.2 lakh.

Example 2 - Outlier fences and what the box plot shows. Monthly sales (₹ lakh) of 12 stores, sorted: 12, 14, 15, 18, 20, 21, 23, 25, 28, 30, 34, 72.

Example 3 - Lie factor of a truncated bar chart. Revenue rose from ₹100 crore to ₹110 crore (a true increase of 10%). The chart's y-axis starts at ₹95 crore, and the bars are drawn 5 mm and 15 mm tall.

Example 4 - Pie vs bar for market share. Shares: A 38%, B 31%, C 16%, D 9%, E 6%.

Example 5 - Choropleth normalisation. Two states report EV registrations: State X 2,40,000 EVs, population 12 crore; State Y 90,000 EVs, population 1.5 crore.

NeedBest chartAvoid
Compare values across categoriesSorted horizontal bar3-D pie, radar
Parts of a whole (2-4 parts)Pie / 100% stacked barPie with 10 slices
Distribution of one numeric variableHistogram, KDE, ECDFBar chart of raw values
Compare distributions of many groupsBox or violin plotMean-only bar chart
Relationship between two numericsScatter (+ LOWESS)Dual-axis line
Trend over timeLine chartBars for continuous time
Value across regionsNormalised choroplethRaw-count choropleth
Matrix of pairwise valuesDiverging heatmapTable of 100 numbers
Composition changing over timeStacked area / 100% stackedMany overlapping lines
LibraryStrengthWeak point
MatplotlibTotal control, publication output, every formatVerbose; defaults look plain
SeabornStatistical charts, faceting, tidy-data APILess control; figure-level/axes-level confusion
Plotly / ExpressInteractive, hover, HTML & dashboardsHeavier output files; static export needs extra engine
AltairDeclarative grammar, clean syntaxLarge datasets need special handling
Power BI / TableauRefreshable business dashboards, no codeLicensed; weaker for custom statistical plots
import matplotlib.pyplot as plt, seaborn as sns, pandas as pd
df = pd.read_csv("placements.csv")          # cols: branch, ctc_lakh, year, gender

fig, ax = plt.subplots(1, 2, figsize=(11, 4), constrained_layout=True)

# left: distribution with Freedman-Diaconis bins
sns.histplot(data=df, x="ctc_lakh", bins="fd", kde=True, ax=ax[0])
ax[0].set(title="CTC distribution", xlabel="CTC (Rs lakh)", ylabel="Students")
ax[0].axvline(df.ctc_lakh.median(), ls="--", color="black")

# right: compare branches - distribution, not just the mean
order = df.groupby("branch").ctc_lakh.median().sort_values(ascending=False).index
sns.boxplot(data=df, x="ctc_lakh", y="branch", order=order, ax=ax[1])
ax[1].set(title="CTC by branch (median-sorted)", xlabel="CTC (Rs lakh)", ylabel="")

fig.savefig("ctc.svg", bbox_inches="tight")  # vector for the report
plt.close(fig)

# figure-level: small multiples - note NO ax= argument
g = sns.relplot(data=df, x="year", y="ctc_lakh", col="branch", hue="gender",
                kind="line", errorbar=("ci", 95), col_wrap=3, height=2.8)
g.set_axis_labels("Year", "Mean CTC (Rs lakh)")

# correlation heatmap: diverging map centred at zero
num = df.select_dtypes("number")
sns.heatmap(num.corr(numeric_only=True), vmin=-1, vmax=1, center=0,
            cmap="coolwarm", annot=True, fmt=".2f")

Where it is used

Interview questions

Common mistakes

Related topics

Python for data analysis: NumPy and pandas · Data cleaning and feature engineering · Statistics: descriptive measures and distributions · SQL queries and joins · Exploratory data analysis and hypothesis testing · Business intelligence and dashboarding (Power BI, Tableau)

Open in the Knowledge reader →Find jobs →