1Getting data in
Pandas reads directly from a URL. You never have to download the file manually.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn-v0_8-whitegrid') # consistent clean look for every plot
df = pd.read_csv("https://example.com/data.csv") # CSV
df = pd.read_json("https://example.com/data.json") # JSON
| Format | What it is | Reader |
|---|---|---|
| CSV, comma-separated values | One row per line, values separated by commas | pd.read_csv() |
| JSON, JavaScript object notation | Hierarchical, nested structure | pd.read_json() |
Everything in Python goes through a DataFrame. That is the shape pandas and Matplotlib both expect, so the first job with any source is getting it into one.
Time series
parse_dates
parse_dates, dates are strings, and strings sort alphabetically rather than chronologically. "10-Feb" comes before "2-Jan" in an alphabetical sort, so the line jumps between random points and the chart is meaningless. set_index('date') then makes the date the axis, so time-based plotting and slicing work.Selecting one column, df['temp_max'], is called subsetting, and it is how you plot one series out of a wide table.
Multiple plots in one figure
axes[0], axes[1]. With a grid you must give both, row then column: axes[0, 1], or the code cannot tell where the plot goes. Hover any cell in the grid to see its index.| Element | Meaning |
|---|---|
plt.subplots(rows, cols) | Creates a grid of axes |
axes[0], axes[1] | Select a subplot when there is a single column |
axes[0, 1] | Select a subplot in a grid, row then column |
sharex=True | All subplots share one x-axis, so dates align vertically |
fig.suptitle() | Title for the whole figure, not one subplot |
plt.tight_layout() | Fixes overlapping labels and titles |
Why stacked time series need sharex
Plotting from a DataFrame, and the random walk
cumsum()Encoding a third variable on a scatter
s= turns a scatter into a bubble chart
Geographic data with GeoPandas
column= colours regions by a data value, which produces a choropleth, and Chapter 2's population caveat applies here too. legend_kwds controls legend orientation and label, and a horizontal legend often fits better than a vertical one that eats width.cities = pd.DataFrame({'city': ['New Delhi', 'New York', 'Tokyo'],
'lat': [28.6, 40.7, 35.7],
'lon': [77.2, -74.0, 139.7]})
gdf_cities = gpd.GeoDataFrame(
cities, geometry=gpd.points_from_xy(cities['lon'], cities['lat']))
ax = world.plot(color='lightgrey') # base layer
gdf_cities.plot(ax=ax, color='red') # overlay on the same axes
plt.show()
- Build the geometry from longitude and latitude with
points_from_xy. Longitude first, since it is the x coordinate. - Pass
ax=axto draw the second layer onto the same axes. Without it you get two separate maps. - You do not always need the full map outline, because plotting the points alone often reads as the region anyway, through the closure principle from Chapter 1.
Curve fitting and extrapolation
Forecasting is a visualisation problem as much as a modelling one: you fit a functional form to existing data and extend it forward.
You could run the model and report a number. Showing actual and predicted on one chart does something the number cannot: it lets the audience see how closely the model tracks reality. That is what earns acceptance for the forecast, which is Chapter 2's acceptance principle applied to modelling.
Key points
- Reading CSV and JSON, including directly from a URL.
- Why
parse_datesandset_indexare needed before plotting a time series. plt.subplots(rows, cols), and indexing with one index against two.- What
sharex=Truedoes and why stacked time series need it. fig.suptitle()againstax.set_title(), and whattight_layout()fixes.cumsum()and the random walk, and why an apparent trend can be pure chance.- Encoding a third variable through marker size, and why the size must be scaled.
- What makes a GeoDataFrame different from a DataFrame.
gpd.read_file(), colouring bycolumn=, and building points withpoints_from_xy.- Passing
ax=axto overlay layers on one map. np.polyfitandnp.poly1d, and what the degree controls.- The polynomial against linear comparison, and why the choice of form changes the forecast so much.
- Why the fitted curve is plotted alongside the actual data rather than reported as a number.