5.4.16Scientific Computing (Python)

2D plots — line, scatter, bar, histogram, contour, imshow

2,204 words10 min readdifficulty · medium

WHY these six exist (the decision tree)

WHAT distinguishes the six: what they assume about your data.

Plot Data shape Implied meaning Key question
plot y vs ordered x points are connected (a function/series) "trend?"
scatter (x, y) pairs points are independent "correlation/cluster?"
bar category → value discrete groups "which is biggest?"
hist one array of samples frequency of value ranges "what's the distribution?"
contour grid Z[i,j]=f(x,y) a height map (level curves) "shape of surface?"
imshow 2D array of values colored pixel grid "the matrix/image itself?"

1. Line plot — ax.plot

import numpy as np
import matplotlib.pyplot as plt
 
x = np.linspace(0, 2*np.pi, 200)   # 200 pts -> smooth
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y, color="tab:blue", lw=2, label="sin x")
ax.set_xlabel("x (rad)"); ax.set_ylabel("sin x")
ax.legend(); ax.grid(True)
plt.show()

2. Scatter — ax.scatter

rng = np.random.default_rng(0)
x = rng.normal(size=100)
y = 2*x + rng.normal(size=100)        # correlated
ax.scatter(x, y, s=30, c=x, cmap="viridis", alpha=0.7)

3. Bar — ax.bar

labels = ["A", "B", "C"]; vals = [5, 9, 3]
ax.bar(labels, vals, width=0.6, color="tab:orange")

WHY categorical x: Matplotlib places category kk at integer position kk and prints the label under it.


4. Histogram — ax.hist

data = rng.normal(loc=0, scale=1, size=5000)
ax.hist(data, bins=40, density=True, color="tab:green", alpha=0.8)

5. Contour — ax.contour / ax.contourf

xs = np.linspace(-3, 3, 100); ys = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(xs, ys)
Z = np.exp(-(X**2 + Y**2))          # a Gaussian bump
cs = ax.contour(X, Y, Z, levels=8, cmap="plasma")
ax.clabel(cs, inline=True)          # label each level
# ax.contourf(...) fills between levels with color instead of lines

6. imshow — ax.imshow

ax.imshow(Z, origin="lower", extent=[-3,3,-3,3], cmap="inferno", aspect="auto")
fig.colorbar(ax.images[0], ax=ax, label="f(x,y)")

Putting it together (the cheat figure)

Figure — 2D plots — line, scatter, bar, histogram, contour, imshow


Recall Feynman: explain to a 12-year-old

Think of graph paper. Line: I plot a few dots and connect them like a join-the-dots puzzle — good for "how did temperature change all day." Scatter: I just sprinkle dots, no lines — good for "do taller kids weigh more?" Bar: tall blocks for each thing — "who scored most goals?" Histogram: I sort everyone's height into boxes (140-150cm, 150-160cm...) and count how many in each box — shows the shape of the group. Contour: like a treasure map showing hills with rings. imshow: I color every little square of graph paper by its number, like a paint-by-numbers — that's how a photo or a heatmap works.


Flashcards

When do you use scatter instead of line?
When points are independent (no meaningful order/connection), or to encode extra variables via point color/size.
A line plot looks smooth — what actually makes it smooth?
Many closely-spaced sample points; it's still straight segments between consecutive points.
Difference between a bar chart and a histogram?
Bar = one bar per category you give; histogram = bars are auto-computed bins counting how many samples fall in each value-range.
Histogram bin width formula for B equal bins?
h=(maxmin)/Bh = (\max-\min)/B.
What does density=True do in hist and why?
Scales heights so total area = 1 (PDF estimate); each height becomes cj/(nh)c_j/(nh).
What is a contour line at level c, mathematically?
The set of points {(x,y):f(x,y)=c}\{(x,y): f(x,y)=c\}.
Why must you call np.meshgrid before contour?
contour needs Z as a 2D grid over every (x,y) pair; meshgrid builds the X, Y coordinate tables.
What does imshow show and how are rows/cols mapped?
A 2D array as colored cells; rows = y, columns = x; value → color.
Why might an imshow image appear upside-down and the fix?
Default origin="upper" puts row 0 at top; use origin="lower" for math orientation.
Why prefer ax.plot(...) over plt.plot(...)?
Object-oriented API gives explicit control, essential with multiple subplots.
What does extent do in imshow?
Maps array indices to real coordinate ranges [xmin,xmax,ymin,ymax].
5-step ritual to make any plot?
fig,ax = subplots; ax.(...); set labels; legend/colorbar; plt.show().

Connections

Concept Map

mapped to pixels

contains

every method is ax.something

ordered x connected

independent x,y pairs

categories

one sample array

scalar field z=f x,y

2D array as cells

draws segments between points

many points

80/20 core

80/20 core

80/20 core

Data numbers

Matplotlib plot

Figure canvas

Axes coordinate system

Line plot

Scatter

Bar

Histogram

Contour

imshow

Dot-to-dot segments

Illusion of curve

Most used trio

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, har 2D plot basically ek hi cheez karta hai — numbers ko picture me badalna. Bas farq yeh hai ki tum data ko kaise samajhna chahte ho. Agar koi cheez time ke saath badal rahi hai (ordered x), to line plot — dots ko jodke trend dikhata hai. Agar points independent hain, jaise "lambe log zyada heavy hote hain kya?", to scatter use karo, koi line mat jodo. Bar chart categories ke liye hai — "kis ne sabse zyada goal maare". Aur histogram sabse zyada confuse karta hai: yeh bar chart NAHI hai tumhare data ka, yeh batata hai ki kitne samples kis range (bin) me aaye — yaani data ki shape/distribution.

Do advanced wale: contour ek mountain ki tarah hai — z=f(x,y)z=f(x,y) ko alag-alag heights pe slice karke rings banata hai, bilkul map me elevation lines jaise. Iske liye pehle np.meshgrid se 2D grid banana zaroori hai, warna error aayega. Aur imshow matrix ya image ko colored squares me dikhata hai — har cell ka value ek color ban jaata hai (heatmap). Yaad rakho: imshow me default origin upar hota hai, isliye math matrix dikhane ke liye origin="lower" lagao, warna image ulti dikhegi.

Practical advice: hamesha fig, ax = plt.subplots() use karo aur ax.plot(...) likho, plt.plot nahi — kyunki multiple subplots me explicit control chahiye. Aur axes ko label karna mat bhoolna (units ke saath), warna plot useless hai. 80/20 rule: real life me 90% kaam line + scatter + histogram se ho jaata hai, baaki teen jab specifically surface ya image dikhana ho tabhi.

Go deeper — visual, from zero

Test yourself — Scientific Computing (Python)

Connections