Turning a summarised table into a chart that shows the pattern clearly, with matplotlib for control and seaborn for speed.
Programming for Data Science · University of the Philippines Cebu
The fig, ax foundation every Python chart is built on.
Line, bar, scatter and histogram, and when each one applies.
Statistical plots directly from a DataFrame, and honest design.
A chart is how an analysis reaches other people. A good chart answers its question quickly.
Matplotlib is a blank canvas on which every part is drawn by hand; seaborn is a chart template that takes a table and the names of the columns to use.
Make a labelled, honest chart from a DataFrame.
The whole picture: the canvas that is sized and saved as an image file.
e.g. fig.savefig("chart.png")
One plotting area inside a figure, with its own x and y axis. Data are drawn on it.
e.g. fig, ax = plt.subplots() gives one figure and one axes
To draw data onto an axes; ax.plot draws points joined by a line.
e.g. ax.plot([2021, 2022], [12, 15])
The symbol drawn at each data point: a dot, a square, a triangle.
e.g. marker="o" puts a dot on every point
Text that names an axis or the chart, ideally with the unit.
e.g. ax.set_ylabel("Sales (₱)")
The small key that says which colour or marker means which group.
e.g. ax.legend() after label="Cebu"
One of several small charts arranged in a grid inside one figure.
e.g. plt.subplots(1, 2) makes two side by side
Bars that count how many values fall in each range (bin) of one column.
e.g. ax.hist(scores, bins=5)
The basic Python charting library, in which every part is drawn and labelled explicitly.
e.g. import matplotlib.pyplot as plt
A library built on matplotlib that draws statistical charts from a DataFrame in one call.
e.g. sns.histplot(data=df, x="pop") (Colab, not the browser lab)
The groupby in week 7 gave numbers per region. Which region is largest, and by how much, is much faster to see in a bar chart than in a column of digits.
Exact, but every row must be read to compare.
Approximate, but the pattern is visible immediately.
John D. Hunter, analysing EEG brain recordings, cannot find a Python plotting library, so he writes one.
Hunter dies in August; the community carries the project on.
Michael Waskom’s first releases: statistical charts built on matplotlib.
NASA funds matplotlib’s continued development.
Hunter had been plotting in MATLAB and moved to Python; matplotlib’s commands still resemble MATLAB’s.
seaborn does not replace matplotlib: it calls matplotlib to draw, so the two are used together.
Sourcematplotlib.org: History; Wikipedia: Matplotlib; seaborn release notes; pyplot docs (“MATLAB-like”)
matplotlib downloads in September 2026.
seaborn downloads in the same month.
The Event Horizon Telescope team used matplotlib for visualisations behind the first black-hole image.
pandas’ own .plot() draws with matplotlib, so every pandas chart is a matplotlib chart.
SourceDownloads: pypistats.org, without mirrors, retrieved 11 Oct 2026; black hole: Wikipedia: Matplotlib
As in weeks 5 to 7, a block with a ▶ Run / Edit button runs in the browser and can be changed. A chart appears as a picture under the code. The first run downloads Python, pandas and matplotlib, which takes 10 to 20 seconds.
seaborn is not available in the browser, and the flood data cannot be downloaded there. Those blocks have no button; the companion notebook runs them.
pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browsert.dtypeseach column’s type: str on the laptop, object in the browserThe foundation under every Python chart.
Weeks 6 and 7 reduced tables to summary numbers. This part draws them: matplotlib is the Python library (a package of ready-made code loaded with import) that draws charts, one instruction at a time.
plt.subplots() returns a figure (the canvas)
and an axes (the plot itself). Methods on ax draw and label.
ax.plot draws points joined by a lineA method (week 4) is a function that belongs to an object, called with a dot: ax.plot(…).
ax.plot to ax.bar and run again.Result on the lecture laptop (select to reveal)
One line rising from 12 to 24, with a dip in 2023. The ticks read 2021.0, 2021.5, 2022.0, …: matplotlib treats the years as ordinary numbers. With ax.bar, the same five values become five bars. The next slide shows the line chart.
fig, ax = plt.subplots()a figure (the whole picture) and one axes (the plotting area) inside itax.plot(years, sales)draw a line through the five points, x from years, y from salesplt.show()display the finished chart
sales dip in 2023, then climb. The x axis shows 2021.5 and 2022.5 because matplotlib treats years as ordinary numbers, and neither axis says what it measures yet: labels come a few slides on.
Run with the week-8 lab’s lists: years = [2021, 2022, 2023, 2024, 2025], sales = [12, 15, 14, 20, 24]. Every chart in this deck is the real output of the code on the slide before it.
The rest of Part A charts the 34,079 flood control projects, with week 6’s duration column: days from start to completion.
pd.read_csv(url)?pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.
The browser cannot download the data, so the flood blocks have no Run button; the companion notebook runs them, and each chart that follows was drawn by its slide’s code.
requests.get(url)download the whole table in one requestdf["duration"] = …days from start to completion; NaN where a date is missing(34079, 16)34,079 projects; 15 columns from the file plus durationplt.plot() draws onto whatever figure is "current", which becomes ambiguous once there are two. Requesting the objects explicitly avoids that ambiguity.
Saving and sizing happen on fig. Drawing and labelling happen on ax.
plt.subplots(figsize=(8, 5))one figure, 8 by 5 inches, with one axesax.scatter(df.budget, df.duration, alpha=0.05)one dot per project; alpha makes each dot 95% transparentset_xlabel / set_ylabelname each axis, with its unit
even at alpha=0.05 the left edge is solid blue. Most budgets are small and a few are huge, so nearly every dot is squeezed into the first fifth of the axis. The 1e9 at the bottom right means the ticks are in billions of pesos (0.2 = ₱200 million).
Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.
Two numbers give a grid. axes is then a NumPy array and is indexed like one. Each small chart in the grid is called a subplot.
Panels with different y-limits appear comparable but are not. A shared axis makes a multi-panel figure honest.
plt.subplots(2, 2, …, sharey=True)a 2 × 2 grid of axes that share one y scaleaxes[0, 0]row 0, column 0: the top-left axes; axes.flat loops over all fourfig.tight_layout()space the panels so labels do not overlap
budget piles into the first one or two bars: most projects are small, a few are enormous. Because of sharey=True both histograms use the same 0–22,000 scale, so their bar heights can be compared directly.
Only the two hist lines and tight_layout(): the loop then fills the empty panels with whichever columns cols lists. Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.
Overplotting is when dots pile on top of each other until their number can no longer be seen. Every real scatter in this course has too many points. There are three fixes, and the first is usually sufficient.
Transparency shows density at no cost. When that saturates, the plane is binned instead of drawing points.
alpha=0.05, s=4fix 1: faint, small dots, so dense areas look darkerdf.sample(2000, random_state=42)fix 2: plot a reproducible sample of 2,000 projectsax.hexbin(…, xscale="log")fix 3: count the dots in hexagons; budgets of 0 are left out, since log(0) does not exist
alpha=0.05, s=4, then set_xscale("log")
hexbin(…, xscale="log"), budgets above 0once the budget axis is logged, both show bigger budgets tending to take longer, and budgets bunching at round numbers (the vertical stripes). The darkest hexagon is the most common kind of project.
Here x is df.budget and y is df.duration. Run as first written, hexbin followed by set_xscale("log") drew an empty chart, so the code passes xscale="log" to hexbin; it refuses the 939 projects with a ₱0 budget, so those are dropped first.
Title, axis labels with units, and the data. Without any of the first three, a reader must guess what the chart shows.
A label is the text that names an axis or the chart; the small numbers along each axis are ticks.
Units belong in the axis label: "Sales (₱)", not only "Sales".
Three lines make an unlabelled plot interpretable. Labels are needed every time, because the meaning of the axes is easily forgotten later.
A chart without labels is a map without a legend or place names; the shapes are present but their meaning is not.
ax.set_xticks(years) changes.set_title line and run again. What can a reader no longer tell?Result on the lecture laptop (select to reveal)
The x ticks become the five whole years instead of 2021.0, 2021.5, …; both axes now say what they measure. Without the title, nothing says whose sales these are or which years they cover.
ax.set_xticks(years)put a tick at each year, and only thereset_xlabel / set_ylabel / set_titlewhat is across, what is up (with its unit), and what the chart is aboutMatching the chart to the question.
Part A made and labelled a figure. This part covers choosing which picture to draw, because each chart type answers a different kind of question.
| Chart | Shows | Use when |
|---|---|---|
| Line | a trend over time | the x-axis is ordered (dates, steps) |
| Bar | compare categories | a value per named group |
| Scatter | a relationship | two numbers, one point per row |
| Histogram | a distribution | the spread of one number |
The wrong chart hides the answer. A line chart over unordered categories, for instance, implies a trend that does not exist.
A distribution is how the values of one column are spread out: where most of them sit, and how far the extremes reach. A relationship is whether two numbers tend to rise or fall together.
Whether the chart shows a trend, a comparison, a relationship or a spread.
The chart-type examples in Part B use the eight cities from week 7, merged with their land areas, and the total population of each region.
cities.merge(areas, on="city")week 7’s merge: population and area in one table, bothboth.groupby("region")["pop"].sum()the total population of each region’s cities: by_regionSourceLand areas from each city’s Wikipedia article, rounded to whole km²; populations are approximate 2020 census figures.
A line connects ordered points and implies continuity. Bars sit apart and imply separate items to compare.
A line chart resembles a temperature graph through the day, where hours follow each other; a bar chart resembles a height chart, where each bar is a separate person.
plt.subplots(1, 2, …)one row of two axes, side by sidea1.plot(years, sales, marker="o")a line for a trend over time, with a dot on each yeara2.bar(by_region.index, by_region.values)bars to compare categories: one per regionA line chart says "these points are connected in order". It is appropriate only for time or another genuine sequence.
A marker is the symbol drawn at each data point: "o" a dot, "s" a square, "^" a triangle.
Connecting 18 regions implies that Region I leads into Region II. Unordered data require bars.
df.groupby("year").budget.sum() / 1e9total budget per year, in billions of pesosax.plot(…, marker="o")a line through the yearly totals, with a dot on each year2026 0.0the last two years are incomplete: the next slide
the line climbs to a 2024 peak, then plunges to ₱196B in 2025 and to zero in 2026. The chart draws that plunge as confidently as every other year; the next two slides examine whether it is real.
Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.
Either a 47% fall in flood control spending, or an export taken partway through the year.
2026 has one project in it. 2025 has 3,475 against 2024’s 5,553. The dataset was exported mid-period, so the last values are partial, and the chart does not indicate this.
Drop the incomplete periods, or draw them differently (dashed, greyed) and label them. A partial period should not be plotted as if it were complete.
y[y.index <= 2024]keep only the complete yearslinestyle="--", color="grey"draw the incomplete years dashed and grey, so they read as differentax.annotate(…)write a label on the chart, with an arrow to the point it explains
y[y.index <= 2024]
on the left the partial years are gone, so the chart ends at the 2024 peak. On the right they stay but look different: the grey dashes signal “not comparable” before any label is read.
The note was placed with xy=(2025, y[2025]), xytext=(2025.3, 250). Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.
Three decisions turn an unreadable bar chart into a readable one, and none of them is about colour: sort the bars by size, lay them sideways, and start the value axis at zero.
"National Capital Region" rotated 45 degrees is unreadable and takes a third of the figure. barh avoids this at no cost.
.sort_values() / 1e9smallest first, so the longest bar ends up on topax.barh(g.index, g.values)horizontal bars: long region names stay readable
every region name is readable, the longest bar sits on top, and Region III’s bar is about 1.7 times NCR’s, which the eye sees at once without reading a number.
Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.
twinx() ("twin x") puts two scales on one plot: a second y axis on the right that shares the same x axis. It is the easiest way to imply a relationship that is not there, because the author chooses both scales.
Two stacked panels with sharex=True. The comparison survives; the implied correlation (the suggestion that the two lines move together) does not.
ax2 = ax.twinx()a second y axis on the right, sharing the x axisplt.subplots(2, 1, sharex=True)the safer layout: two panels, one above the other, one year axis
twinx(): two scales on one plot
sharex=Trueon the left the lines seem to rise and fall as one, but only because matplotlib stretched each scale to fill the box; a different right-hand scale would pull them apart. On the right each measure keeps its own axis.
counts = projects per year, df.groupby("year").size(); totals = the yearly budget y; the twin axes sit on the spend-per-year chart. Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.
A scatter plots one point per row to reveal whether two numbers move together. A histogram bins one column to show where values cluster.
A histogram cuts the range of values into equal slices called bins (e.g. 0–10, 10–20, …) and draws one bar per bin, as tall as the number of values that fall in it.
A histogram resembles grouping students by height band, counting how many are 150–155 cm, how many 155–160 cm, and so on.
bins=5 to bins=2. What does the histogram hide now?Result on the lecture laptop (select to reveal)
No clear pattern (correlation 0.24): Davao has the largest area, 2,444 km², but fewer people than Quezon City’s 172 km². With 5 bins the counts are 4, 1, 2, 0, 1; with 2 bins only 5 and 3 remain, and the single city above 2.4 million (Quezon City) disappears into the upper bar.
a1.scatter(both["area_km2"], both["pop"])one dot per city: area across, population upa2.hist(both["pop"], bins=5)count the cities in 5 equal-width population rangesWhich chart shows the spread of exam scores across one class?
C — histogram.
A histogram bins one column to show its distribution — where scores cluster and how wide they spread. A line implies order; a scatter needs two numbers.
Spread of one number → histogram. It is the standard chart for the shape of one column.
One column's shape → histogram.
Next: plotting with seaborn.
Statistical charts, straight from a DataFrame.
Any chart can be built in matplotlib line by line. seaborn is a second library, built on top of matplotlib, that draws common statistical charts from a DataFrame in one call. (The in-browser lab has matplotlib only; seaborn runs in Colab.)
The whole frame is passed, with a column named for each axis. seaborn reads the data directly, applies sensible defaults and labels the axes.
matplotlib takes two lists of numbers. seaborn takes the whole table and the column names for each axis ("region" across, "pop" up).
sns.barplot(data=both, x="region", y="pop")name the table once, then the columns; by default the bar shows each region’s mean, with an error barsns.scatterplot(…)the same style for a scatter: columns by name, axes labelled automaticallyHalf of seaborn’s functions return a figure, not an axes.
This distinction explains nearly every seaborn error message that beginners encounter.
ax=The *plot functions that end in plot and take ax= are axes-level. relplot, displot, catplot are figure-level.
ax=ax"draw on this axes": the one made with plt.subplots()col="region", col_wrap=4one panel per region, four panels per rowg.fig / g.axesg is the grid seaborn built; these give its figure and its axesrelplot(…, ax=ax)if ax= is passed anyway, seaborn prints a warning that relplot does not accept it and ignores it: the chart appears in a new figure, not on the given axesFor one chart placed inside a controlled layout, axes-level is used. For the same chart repeated per group, figure-level is used and builds the grid.
There is no col= on scatterplot. This is the usual reason for writing manual subplot loops.
col="region", col_wrap=6one panel per region, six panels to a rowg.set(xscale="log")the same log budget axis on every panelg.savefig(…)a figure-level plot is saved through its own object, not plt.savefig
every panel shares the same axes, so regions compare at a glance: Region III and NCR are dense, Central Office has only a handful of dots. Two long region names collide in the bottom row; that is seaborn’s default output.
d is the 2,000-row sample from the overplotting slide, df.sample(2000, random_state=42). Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.
| Function | Draws | Additional feature |
|---|---|---|
sns.histplot | a histogram | optional density curve (a smooth line tracing the bars’ shape) |
sns.boxplot | spread per group | median + outliers at a glance |
sns.scatterplot | a relationship | hue= colours by a category |
sns.barplot | a value per group | a confidence bar (a thin line showing how uncertain each average is) automatically |
These are the same charts as in matplotlib, with fewer lines and better defaults. Guideline: seaborn first, matplotlib for fine control.
A box plot draws each group's middle half of
values as a box, with a line at the median and dots for unusual values (outliers).
hue= means "colour by this column".
hue="region" colours points by group with no extra code.
A legend is the small key that says which colour or marker means what. A series is one set of data drawn as one line or one set of dots. A legend on a single-series chart is noise. On a multi-series chart it is essential, and its placement matters.
Two or three series read better annotated at their right-hand end than via a legend the eye has to travel to.
label="Region III"the name the legend shows for this lineax.legend(loc="upper left", frameon=False)draw the legend in a corner, without a boxbbox_to_anchor=(1.02, 1)outside the right edge: save with bbox_inches="tight" or it is cropped (next slide)
loc="upper left", frameon=False
bbox_inches="tight"inside, the key fits the empty top-left corner. Outside, a default save cuts the names off at the image edge; saving with bbox_inches="tight" brings the whole key back.
x = the years; a, b = Region III’s and NCR’s yearly budget in PHP billions, from df.groupby(["year", "region"]).budget.sum(). Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.
Consistent figures across a report come from one call, not from repeating the same arguments in every chart.
whitegrid for anything with a y-scale to read against; ticks for scatter plots where a grid adds nothing.
style="whitegrid"white background with light grid linespalette="colorblind"the set of colours used for groups, chosen to stay distinguishable for colour-blind readerscontext="talk"scale all text and lines for a projector| Symptom | Cause | Fix |
|---|---|---|
| Nothing appears in the notebook | No plt.show(), or a non-interactive backend | Add %matplotlib inline |
| Labels cropped in the saved file | Default save clips outside the axes box | bbox_inches="tight" |
relplot ignores ax= (with a warning) | It is figure-level and owns its figure | Use scatterplot(ax=ax) |
| Panels overlap each other | Default spacing does not account for labels | fig.tight_layout() |
All four are layout problems, not data problems — so they are worth memorising. In each case the chart is correct but its frame is not.
%matplotlib inline is a notebook command (not Python) that shows charts under the cell. A backend is the part of matplotlib that turns a figure into pixels on a screen or in a file.
A cropped y-axis makes a 2% gap look large. Bars must begin at 0.
One clear message per chart is more effective than ten competing series.
Colour should encode meaning, not decorate. Keep it readable for everyone.
As in DS 227 (the companion course), presenting data is a choice. The choice of axis shapes the conclusion a reader draws.
A design choice that inflates the effect misrepresents the data.
A bar’s meaning is its length. Cutting the axis changes every length while the numbers remain technically correct.
A line chart encodes position, not length, so a non-zero baseline is acceptable and often necessary to show the change.
(df.status == "Completed").groupby(df.region).mean()the completion rate of each region: True counts as 1ax.set_ylim(…)first 0 to 1 (honest), then 0.6 to 0.95 (truncated)0.656 / 0.920Region IX and Region XII: a 1.4× ratio that the truncated axis draws as about 5.7×
set_ylim(0, 1)
set_ylim(0.6, 0.95)on the left the bars differ modestly, which is accurate. On the right the same numbers make Region XII look almost six times Region IX. The names crashing along the bottom are the long-label problem that barh solves.
rates = each region’s share of projects with status Completed, sorted. Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.
On a log axis (short for logarithmic), equal distances are equal ratios, not equal amounts. This is a different kind of chart and must be labelled as such.
Not only in the caption: the label stays with the image when it is copied into a slide.
ax.set_xscale("log")equal steps on the axis now mean equal ratios: 10M to 100M is as wide as 100M to 1B"Budget (PHP, log scale)"say so in the label, or readers assume a linear scale
the same dots as the first scatter now fill the width. The ticks go 106, 107, 108, each ten times the last, and the axis label says so.
The first scatter (figsize=(8, 5), alpha=0.05) with these two lines added. Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.
About 8% of men have some form of colour-vision deficiency. Red-green deficiency is the most common, and red-green is also a common default.
A colormap (cmap) is a colour scale that turns numbers into colours, like a heat map from pale to dark.
Sequential for magnitude, diverging for a meaningful midpoint, qualitative for unordered categories. Using the wrong family misstates the data.
cmap="viridis"sequential: low to high, readable in colour-blind vision and in greyscalecmap="RdBu_r"diverging: two colours meeting at a middle value (here 0)A reader should not have to find the conclusion in the dots, so it is marked on the chart.
Two arrows mean the chart has two messages, which usually means it should be two charts.
q1, q3 = d.budget.quantile([.25, .75])the cheapest and the most expensive quarter of the projects that have a durationax.annotate(text, xy=…, xytext=…)the note, the point it explains, and where the text sitsax.set_title(f"…")the title states the finding, computed from the data: 269 against 119 median days
the title states the finding and one arrow points at the one group being discussed, so the message is clear without searching through the dots. The note runs past the right edge because xytext doubles x0; a tight save keeps it in the file.
x0, y0 = Central Office’s median budget (₱144.5M) and median duration (448 days), on the log-scale scatter from the previous slides. Data: DPWH flood-control projects (BetterGov.ph mirror, CC0), 34,079 rows; 27,664 have a duration.
tight_layout() stops labels clipping; savefig with a
higher dpi exports a crisp image for a report or slide.
dpi means "dots per inch": more dots give a sharper, larger image file.
fig.tight_layout()make room for the labels before savingfig.savefig("pops.png", dpi=150)write the chart to a file at 150 dots per inchplt.show()display it in the notebook as wellThe default save clips anything outside the axes box — which is exactly where rotated tick labels and legends live.
150 for a slide, 300 for print. The default 100 looks soft on any modern screen.
bbox_inches="tight"trim the image to everything drawn, so nothing outside the axes is cropped"area_pop.pdf"a vector file: it stays sharp when zoomedplt.close(fig)free the figure’s memory; a script that saves many charts should close each| Check | Why it matters |
|---|---|
| Both axes labelled, with units | "Budget" is not a unit. "Budget (PHP)" is. |
| Title states the finding | "Larger projects take longer" is more informative than "Budget vs Duration". |
| Bars start at zero | Length is the encoding; truncating it misstates ratios. |
| Log scales declared in the label | Otherwise the reader assumes linear distances. |
| n stated somewhere | "27,664 projects with a completion date" — the denominator is part of the claim. |
| Saved with bbox_inches="tight" | Otherwise the labels are cropped off. |
The six checks take about a minute. They distinguish a chart that supports an argument from one that raises questions.
Scatter budget against duration with subplots(). Fix the overplotting with alpha, and log the x-axis.
Both axes with units, a title that states a finding rather than naming the variables.
Rebuild as relplot with col="region", col_wrap=6. Confirm the axis limits are shared.
PNG at dpi=150 with bbox_inches="tight". Open the file and check nothing is cropped.
Step 4 catches more problems than any other step. Charts that look correct inline are often cropped once saved.
sns.relplot(data=d, x=..., y=..., ax=ax) gives a warning, and the axes stay empty. Why?
scatterplot, boxplot, histplot) draw onto a supplied axes. Figure-level ones (relplot, displot, catplot) build and own their whole figure — which is what lets them facet with col=. Use scatterplot(..., ax=ax), or drop ax= and use g.fig afterwards.Completion rates across regions run from 65.6% to 92.0%. What is the effect of ax.set_ylim(0.6, 0.95) on a bar chart?
Grouping, charting, labelling and saving form the whole pipeline from a table to a report-ready figure.
.sort_values() and run again. What becomes harder to see?Result on the lecture laptop (select to reveal)
Luzon: 5,173,000 people, 55% of the eight cities’ total (Mindanao 27%, Visayas 18%). Without sorting, the bars follow alphabetical order (Luzon, Mindanao, Visayas), so the ranking must be read off by eye.
.sort_values()smallest first, so the longest bar sits on topf"… {share['Luzon']:.0%} …"the title states the finding, computed from the dataA bar chart's y-axis starts at 90 instead of 0. What is the risk?
B — it exaggerates small differences.
Bar length encodes value, so a cropped baseline makes a tiny gap look huge. Bars must start at zero; a line chart may crop, since it encodes position, not length.
Bars encode length and always start at zero. This is the most common error in chart design.
Bar baseline = 0, always.
The lab builds a line, bar, scatter and histogram from a real dataset with matplotlib and seaborn, labels each properly and exports one to a file. ~45 minutes.
plt.subplots, the four chart types, axis labels, and
sns one-liners.
The in-browser lab runs matplotlib only (seaborn is not installed there), so the seaborn one-liners are for Colab.
Use plt.subplots(1, 2) to place two charts side by side.
fig, ax = plt.subplots(), then draw and label on ax.
Line (trend), bar (compare), scatter (relate), histogram (spread).
One-line statistical plots from a DataFrame, designed honestly.
In summary: match the chart to the question, always label the axes, and do not let the design overstate the data.
Convert a summary into a chart that a reader can trust at a glance.
ax.plot joins points with a line"o", "s")twinx); easy to mislead withax=) / builds its own figureFinish the Week 8 lab and submit it. Every chart must have a title and labelled axes.
seaborn "An introduction to seaborn" — seaborn.pydata.org/tutorial/introduction.
Everything here is linked on the course page beside this deck.
Data sources: files, SQL databases and web APIs.
Beyond the CSV: reading JSON and Excel, pulling rows from a SQL database, and fetching live data from a web API.
DS 208 · Programming for Data Science