The Time Capsule on the Shelf
When Packt published Python Data Visualization Cookbook, Second Edition in November 2015, the Python data stack looked radically different from today. The book’s 70-plus recipes assume Python 2.7, recommend virtualenv and virtualenvwrapper for isolation, and treat Anaconda as a beginner-friendly distribution rather than the ecosystem anchor it became. Libraries that dominate modern workflows – venv, conda, poetry, polars, pyarrow, Altair, Plotly Express, Dash, Streamlit, cartopy, geopandas – are entirely absent. The geospatial chapter builds on Basemap, unmaintained since 2019. The web chapter uses Google Visualization API’s deprecated jsapi loader. Every code snippet uses print statements, xrange, and the discouraged pylab interface.
Yet the book remains worth studying. Its authors – Igor Milovanović, a Linux systems engineer; Dimitry Foures, a Cambridge-trained applied mathematician; and Giuseppe Vettigli, a machine learning researcher – structured their recipes around a pipeline philosophy: find data, read and clean it, select a visualization, produce comprehensible output. That pipeline, and the architectural reasoning behind it, has outlasted the specific tools.
Environment Reproducibility Before It Was Standard
The opening chapters advocate a discipline that feels familiar today: one virtual environment per project, a requirements.txt pinned by pip freeze, and deterministic reproduction across development, staging, and production. The authors acknowledge three installation paths – OS package managers, source builds, and prepackaged scientific distributions – recommending the last for beginners. That recommendation still holds, though the distribution landscape has consolidated around conda and mamba.
They also document matplotlib’s three-tier configuration cascade: project-level ./matplotlibrc, user-level ~/.matplotlib/matplotlibrc, and system-wide files, with precedence flowing project > user > system. The advice to keep a project-level matplotlibrc for shareable styling remains best practice, now complemented by .mplstyle files that the book also introduces.
Matplotlib’s Architecture: The Mental Model That Persists
The book’s deepest value lies in its systematic exposition of matplotlib’s object model. It distinguishes three layers: the stateful pyplot interface (MATLAB-like convenience), the frontend abstract base classes (Figure, Axes, Artist, Renderer, FigureCanvas, Event), and the concrete backend drivers (backend_agg, backend_pdf, backend_ps, etc.). This hierarchy explains why pyplot.figure() is preferred over direct Figure instantiation – the former manages rcParams, figure managers, and background events automatically.
The transformation framework receives particularly clear treatment. Data coordinates flow through transData to axes coordinates (transAxes), then to figure coordinates (transFigure), finally reaching display space. The authors demonstrate ScaledTranslation for DPI-independent annotation offsets (points, 1/72 inch) and ScaledTransformation for DPI-scaled positioning via Figure.dpi_scale_trans. Custom shapes use Path vertices with MOVETO, LINETO, CLOSEPOLY codes rendered through PathPatch. These mechanisms are unchanged in current matplotlib versions.
LaTeX rendering via text.usetex=True works only with the Agg, PS, and PDF backends (the book notes this limitation; modern SVG backend support came later). The built-in mathtext parser covers a substantial subset of LaTeX math syntax without external dependencies – a fallback that still saves countless TeX installations.
Data Ingestion as a Spectrum of Trade-offs
Chapters 2 and 3 present a graded toolkit that maps to real decisions practitioners still face. The standard library’s csv module handles dialect detection via csv.Sniffer() and manual encoding in Python 2. xlrd reads Excel with lazy loading (on_demand=True) and converts date floats via xldate_as_tuple – though xlrd dropped .xlsx support in 2020, replaced by openpyxl and pandas.read_excel. Fixed-width files use struct.Struct.unpack_from for C-speed parsing with rigid masks. HTTP access prefers requests over urllib2 for its seamless session handling.
Pandas enters as the “de facto standard” for manipulation, with the authors explicitly framing its vectorized column arithmetic as the key advantage for exploratory cleaning. They contrast a custom CLI exporter’s dispatch pattern (import_data → write_data → format-specific writers) against Pandas’ three-line read-transform-write cycle and the DB-API/sqlite3 pathway. That progression – stdlib → specialized parsers → Pandas → database drivers – still reflects the dependency-minimization versus expressive-power trade-off, even as file formats have shifted toward Parquet and Arrow.
Cleaning as Domain Work, Not Automation
“Cleaning cannot be fully automated,” the authors state bluntly. Their outlier detection centers on Median Absolute Deviation (MAD) with a modified z-score threshold of 3.5, citing Iglewicz and Hoaglin’s NIST Handbook methodology. The formula – 0.6745 * (x – median) / MAD > 3.5 – flags univariate outliers robustly. Box plots and scatter plots complement the numerical test.
Categorical normalization (“OH”/”Ohio”/”OHIO”) requires manual replacement or tools like OpenRefine; no library solves this generically. For large files, they demonstrate iterator-based chunking (1,000-line blocks via seek/tell/next) and tail-streaming (seek to end, readline, sleep polling) to avoid full memory loads. Parallel and MapReduce alternatives are noted but not detailed – a gap that persists in many introductory texts.
Signal Generation and Smoothing for Validation
The book generates synthetic data from nine distributions (uniform, triangular, beta, exponential, gamma, lognormal, normal, Pareto) via 1,000-sample histograms. A random-walk price series (100 steps, μ=0.2, σ=1.2) uses cumulative random.normalvariate. Reproducibility comes from random.seed(); cryptographic randomness from random.SystemRandom backed by os.urandom.
Two smoothing approaches illustrate practical signal processing: a simple moving average (window=10) and a convolution method supporting five window types (flat, Hanning, Hamming, Bartlett, Blackman) with boundary reflection via numpy.r_ concatenation to minimize edge effects – attributed to the SciPy Cookbook. The function validates ndim==1, size >= window_len, window_len >= 3. These patterns translate directly to modern scipy.signal and pandas.rolling workflows.
Plot Taxonomy with Perceptual Caveats
The catalog of plot types reads like a design-review checklist. Bar charts support symmetrical and asymmetrical error bars with ecolor and capsize. Pie charts auto-normalize but carry explicit warnings about angle and color perception biases and comparison difficulty. fill_between enables conditional shading via Boolean where arrays and hatch patterns for monochrome output. stackplot requires transposed data (components × observations) and manual legends via Rectangle proxies – though native legend support arrived in later matplotlib versions.
Polar plots (polar=True) distort if the figure isn’t square. 3D plots (Axes3D, bar3d from histogram2d, plot_trisurf) carry the authors’ caution: “more often… more confusing than 2D.” Stream plots use 101×101 mgrid with complex-step notation but cannot update dynamically in the covered version (constituent patches lack awareness of underlying vector data). Wind barbs follow meteorological convention: half-line=5kt, full=10kt, triangle=65kt, with flip_barb for southern hemisphere. Gantt charts build on barh and mdates without dependency tracking.
Statistical Diagnostics: Correlation and Time Series
Scatter plots serve as the primary tool for pairwise correlation detection. The authors offer a heuristic: coefficients between -0.5 and +0.5 are “not valuable” for inferring real connection – though they provide no statistical citation, and significance depends on sample size and distribution. A scatter-histogram hybrid via mpl_toolkits.axes_grid1 uses hard-coded binwidth=0.25. Cross-correlation via plt.xcorr (wrapping numpy.correlate with normed=True referencing zero-lag) and autocorrelation on Google Trends “flowers” data (365 daily points) reveal peaks near 30, 60, 110 days suggesting recurring behavior. The authors caution that correlation ≠ causation and cite Ljung-Box and Box-Pierce as formal follow-ups.
Error bars compute 95% confidence intervals as M ± 1.96×SE, with SE = SD/√N via scipy.stats.sem (the book specifies dtype=np.float64 for np.mean to avoid single-precision inaccuracies). The authors argue CIs are preferable to SD or SE bars because narrow intervals indicate stable means, and they stress explicit labeling of what error bars represent – a practice still widely ignored.
Image Processing and Geospatial as Coordinate Transformation
PIL/Pillow handles batch thumbnailing via a Thumbnailer class (ratio 0.1, IOError catching), channel splitting through NumPy array slicing (img[:,:,0]), and OffsetImage/AnnotationBbox for embedding image glyphs in data coordinates. The authors frame Basemap as a coordinate transformer – “it doesn’t do any plotting”; matplotlib handles rendering. Mercator projection is defined by corner coordinates; ESRI shapefiles read via readshapefile; NetCDF is recommended for partial fetching of large remote datasets via OPeNDAP. This transformer mindset – separate projection logic from rendering – anticipates cartopy’s design.
Web Dashboards and Cloud Publishing as Hybrid Pipelines
The Google Visualization API pipeline converts Python gviz_api.DataTable to JSON, then loads static HTML with the deprecated jsapi loader (google.load(‘visualization’, ‘1’…)). Schema maps column IDs to (“type”, “Label”) tuples; rows become lists of dicts with (float, original_string) pairs. Both the Python library and jsapi are deprecated; modern Charts use loader.js.
Plotly (cloud-based, requiring account/API key, free tier = public charts) demonstrates bar charts from filtered TSV (pandas query/isin/sort), a 3D trefoil knot via “trick”: 50 offset Scatter3d traces around a parametric path with z-dependent RGB coloring – computationally heavy, approximating thickness discretely – and a geographic bubble map via scattergeo with geo.scope=’europe’, hardcoded coordinates, no projection customization. All examples depend on py.plot (online); offline alternatives are not discussed.
What Remains When the Code Won’t Run
The book’s limitations are extensive: Python 2.7 throughout, deprecated libraries (xlrd, Basemap, scikits.audiolab, pylab, Google Visualization API), missing modern tooling, no performance benchmarks, hardcoded non-reusable parameters, statistical claims without citations, platform-specific gaps, no production hardening, Plotly offline absent, and index-only reproducibility. Yet its systematic use of pylab, xrange, print statements, reader.next(), and deprecated modules provides a clear find-and-replace map for porting legacy notebooks.
The enduring utility is architectural. The artist hierarchy, transform pipeline, and backend distinction remain accurate for current matplotlib versions. The data-ingestion decision framework still maps to real trade-offs. The cleaning heuristics – MAD-based outlier flagging, chunked/streaming I/O patterns, the warning against fully automated categorical normalization – are transferable. The plot-type catalog with perceptual caveats serves as a design-review checklist. Project-level matplotlibrc and .mplstyle files remain best practices for team consistency. The text.usetex=True pathway and mathtext fallback are unchanged.
Readers today should treat this book as a conceptual reference, not a current cookbook. Its value lies in teaching the why and where of matplotlib’s architecture, not the how of 2015’s tooling. The pipeline philosophy – find, clean, select, produce – survives every library turnover.