100% found this document useful (2 votes)
67 views

Instant Access To Hands-On Matplotlib: Learn Plotting and Visualizations With Python 3 Ashwin Pajankar Ebook Full Chapters

Plotting

Uploaded by

nguegozvonek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
67 views

Instant Access To Hands-On Matplotlib: Learn Plotting and Visualizations With Python 3 Ashwin Pajankar Ebook Full Chapters

Plotting

Uploaded by

nguegozvonek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Full download ebooks at ebookmeta.

com

Hands-on Matplotlib: Learn Plotting and


Visualizations with Python 3 Ashwin Pajankar

https://ebookmeta.com/product/hands-on-matplotlib-learn-
plotting-and-visualizations-with-python-3-ashwin-pajankar/

OR CLICK BUTTON

DOWLOAD NOW

Download more ebook from https://ebookmeta.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Hands-on Machine Learning with Python: Implement Neural


Network Solutions with Scikit-learn and PyTorch 1st
Edition Ashwin Pajankar

https://ebookmeta.com/product/hands-on-machine-learning-with-
python-implement-neural-network-solutions-with-scikit-learn-and-
pytorch-1st-edition-ashwin-pajankar/

Raspberry Pi Image Processing Programming: With NumPy,


SciPy, Matplotlib and OpenCV, 2nd Edition Ashwin
Pajankar

https://ebookmeta.com/product/raspberry-pi-image-processing-
programming-with-numpy-scipy-matplotlib-and-opencv-2nd-edition-
ashwin-pajankar-2/

Raspberry Pi Image Processing Programming: With NumPy,


SciPy, Matplotlib, and OpenCV 2nd Edition Ashwin
Pajankar

https://ebookmeta.com/product/raspberry-pi-image-processing-
programming-with-numpy-scipy-matplotlib-and-opencv-2nd-edition-
ashwin-pajankar/

Python Unit Test Automation: Automate, Organize, and


Execute Unit Tests in Python Ashwin Pajankar

https://ebookmeta.com/product/python-unit-test-automation-
automate-organize-and-execute-unit-tests-in-python-ashwin-
pajankar/
Python Unit Test Automation: Practical Techniques for
Python Developers and Testers 1 / converted Edition
Ashwin Pajankar

https://ebookmeta.com/product/python-unit-test-automation-
practical-techniques-for-python-developers-and-
testers-1-converted-edition-ashwin-pajankar/

Raspberry Pi Image Processing Programming: Develop


Real-Life Examples with Python, Pillow, and SciPy 1st
Edition Ashwin Pajankar

https://ebookmeta.com/product/raspberry-pi-image-processing-
programming-develop-real-life-examples-with-python-pillow-and-
scipy-1st-edition-ashwin-pajankar/

Learn Quantum Computing with Python and Q#: A hands-on


approach 1st Edition Sarah C. Kaiser

https://ebookmeta.com/product/learn-quantum-computing-with-
python-and-q-a-hands-on-approach-1st-edition-sarah-c-kaiser/

Practical Linux with Raspberry Pi OS: Quick Start 1st


Edition Ashwin Pajankar

https://ebookmeta.com/product/practical-linux-with-raspberry-pi-
os-quick-start-1st-edition-ashwin-pajankar/

Python Data Analytics: With Pandas, NumPy, and


Matplotlib, 3rd Edition Fabio Nelli

https://ebookmeta.com/product/python-data-analytics-with-pandas-
numpy-and-matplotlib-3rd-edition-fabio-nelli/
Hands-on
Matplotlib
Learn Plotting and Visualizations
with Python 3

Ashwin Pajankar
Hands-on Matplotlib
Learn Plotting and Visualizations
with Python 3

Ashwin Pajankar
Hands-on Matplotlib
Ashwin Pajankar
Nashik, Maharashtra, India

ISBN-13 (pbk): 978-1-4842-7409-5 ISBN-13 (electronic): 978-1-4842-7410-1


https://doi.org/10.1007/978-1-4842-7410-1

Copyright © 2022 by Ashwin Pajankar


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Celestin Suresh John
Development Editor: James Markham
Coordinating Editor: Aditee Mirashi
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza,
Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@
springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole
member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc
is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/978-­1-­4842-­7409-­5. For more
detailed information, please visit www.apress.com/source-­code.
Printed on acid-free paper
This book is dedicated to the memory of my teacher,
Prof. Govindarajulu Regeti
(July 9, 1945, to March 18, 2021).

Popularly known to everyone as RGR, Prof. Govindarajulu obtained


his B.Tech in electrical and electronic engineering from JNTU
Kakinada. He also earned an M.Tech and a Ph.D. from IIT Kanpur.
Prof. Govindarajulu was an early faculty member of IIIT Hyderabad
and played a significant role in making IIIT Hyderabad the top-class
institution that it is today. He was by far the most loved and respected
faculty member of the institute. He was full of energy to teach and full
of old-fashioned charm. There is no doubt he cared for every student as
an individual, taking care to know about and to guide them.
He taught, guided, and mentored many batches of students at
IIIT Hyderabad (including the author of this book).
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� xi

About the Technical Reviewer������������������������������������������������������������������������������� xiii


Acknowledgments���������������������������������������������������������������������������������������������������xv

Introduction�����������������������������������������������������������������������������������������������������������xvii

Chapter 1: Introduction to Python 3������������������������������������������������������������������������� 1


Introducing the Python 3 Programming Language����������������������������������������������������������������������� 2
History of the Python Programming Language������������������������������������������������������������������������ 2
Python Enhancement Proposals���������������������������������������������������������������������������������������������� 3
Philosophy of the Python Programming Language������������������������������������������������������������������ 3
Applications of Python������������������������������������������������������������������������������������������������������������� 4
Installing Python on Various Platforms����������������������������������������������������������������������������������������� 4
Installing on a Windows Computer������������������������������������������������������������������������������������������ 5
Installing on Ubuntu/Debian Derivatives��������������������������������������������������������������������������������� 8
Using Python Modes��������������������������������������������������������������������������������������������������������������������� 9
Interactive Mode�������������������������������������������������������������������������������������������������������������������� 13
Script Mode��������������������������������������������������������������������������������������������������������������������������� 14
Using Python IDEs����������������������������������������������������������������������������������������������������������������������� 16
Exploring the Scientific Python Ecosystem��������������������������������������������������������������������������������� 16
Introducing Jupyter Notebook����������������������������������������������������������������������������������������������������� 17
Setting Up Jupyter Notebook������������������������������������������������������������������������������������������������������ 18
Running Code in Jupyter Notebook��������������������������������������������������������������������������������������������� 24
Anaconda������������������������������������������������������������������������������������������������������������������������������������ 28
Summary������������������������������������������������������������������������������������������������������������������������������������ 28

v
Table of Contents

Chapter 2: Getting Started with NumPy������������������������������������������������������������������ 29


NumPy and Ndarrays������������������������������������������������������������������������������������������������������������������ 29
Indexing in Ndarrays������������������������������������������������������������������������������������������������������������������� 32
Indexing in Ndarrays of More Than One Dimension�������������������������������������������������������������� 32
Ndarray Properties���������������������������������������������������������������������������������������������������������������������� 33
NumPy Constants������������������������������������������������������������������������������������������������������������������������ 34
Slicing Ndarrays�������������������������������������������������������������������������������������������������������������������������� 36
Summary������������������������������������������������������������������������������������������������������������������������������������ 37

Chapter 3: NumPy Routines and Getting Started with Matplotlib�������������������������� 39


Routines for Creating Ndarrays��������������������������������������������������������������������������������������������������� 40
Matplotlib������������������������������������������������������������������������������������������������������������������������������������ 45
Visualization with NumPy and Matplotlib������������������������������������������������������������������������������������ 46
Running the Matplotlib Program as a Script������������������������������������������������������������������������������� 52
Summary������������������������������������������������������������������������������������������������������������������������������������ 53

Chapter 4: Revisiting Matplotlib Visualizations������������������������������������������������������ 55


Single-Line Plots������������������������������������������������������������������������������������������������������������������������� 55
Multiline Plots����������������������������������������������������������������������������������������������������������������������������� 58
Grid, Axes, and Labels����������������������������������������������������������������������������������������������������������������� 60
Colors, Styles, and Markers�������������������������������������������������������������������������������������������������������� 66
Object-Oriented Plotting������������������������������������������������������������������������������������������������������������� 71
Subplots�������������������������������������������������������������������������������������������������������������������������������������� 73
Summary������������������������������������������������������������������������������������������������������������������������������������ 74

Chapter 5: Styles and Layouts�������������������������������������������������������������������������������� 75


Styles������������������������������������������������������������������������������������������������������������������������������������������ 75
Layouts��������������������������������������������������������������������������������������������������������������������������������������� 81
Summary������������������������������������������������������������������������������������������������������������������������������������ 85

Chapter 6: Lines, Bars, and Scatter Plots��������������������������������������������������������������� 87


Lines and Logs���������������������������������������������������������������������������������������������������������������������������� 87
Error Bars������������������������������������������������������������������������������������������������������������������������������������ 90

vi
Table of Contents

Bar Graphs���������������������������������������������������������������������������������������������������������������������������������� 92
Scatter Plot��������������������������������������������������������������������������������������������������������������������������������� 95
Summary������������������������������������������������������������������������������������������������������������������������������������ 97

Chapter 7: Histograms, Contours, and Stream Plots���������������������������������������������� 99


Histograms���������������������������������������������������������������������������������������������������������������������������������� 99
Contours������������������������������������������������������������������������������������������������������������������������������������ 103
Visualizing Vectors with Stream Plots��������������������������������������������������������������������������������������� 106
Summary���������������������������������������������������������������������������������������������������������������������������������� 110

Chapter 8: Image and Audio Visualization����������������������������������������������������������� 111


Visualizing Images�������������������������������������������������������������������������������������������������������������������� 111
Image Masking�������������������������������������������������������������������������������������������������������������������� 116
Interpolation Methods��������������������������������������������������������������������������������������������������������������� 116
Audio Visualization�������������������������������������������������������������������������������������������������������������������� 118
Audio Processing���������������������������������������������������������������������������������������������������������������������� 122
Summary���������������������������������������������������������������������������������������������������������������������������������� 123

Chapter 9: Pie and Polar Charts��������������������������������������������������������������������������� 125


Pie Charts���������������������������������������������������������������������������������������������������������������������������������� 125
Polar Charts������������������������������������������������������������������������������������������������������������������������������ 129
Summary���������������������������������������������������������������������������������������������������������������������������������� 134

Chapter 10: Working with Colors�������������������������������������������������������������������������� 135


pcolor()�������������������������������������������������������������������������������������������������������������������������������������� 135
pcolormesh()����������������������������������������������������������������������������������������������������������������������������� 138
colorbar()����������������������������������������������������������������������������������������������������������������������������������� 140
Summary���������������������������������������������������������������������������������������������������������������������������������� 142

Chapter 11: 3D Visualizations in Matplotlib��������������������������������������������������������� 143


Getting Ready���������������������������������������������������������������������������������������������������������������������������� 143
Plotting 3D Lines����������������������������������������������������������������������������������������������������������������������� 145
3D Scatter Plots������������������������������������������������������������������������������������������������������������������������ 146
3D Contours������������������������������������������������������������������������������������������������������������������������������ 147

vii
Table of Contents

Wireframes, Surfaces, and Sample Data���������������������������������������������������������������������������������� 149


Bar Graphs�������������������������������������������������������������������������������������������������������������������������������� 152
Quiver and Stem Plots�������������������������������������������������������������������������������������������������������������� 155
3D Volumes������������������������������������������������������������������������������������������������������������������������������� 158
Summary���������������������������������������������������������������������������������������������������������������������������������� 159

Chapter 12: Animations with Matplotlib��������������������������������������������������������������� 161


Animation Basics���������������������������������������������������������������������������������������������������������������������� 161
Celluloid Library������������������������������������������������������������������������������������������������������������������������ 165
Summary���������������������������������������������������������������������������������������������������������������������������������� 168

Chapter 13: More Visualizations with Matplotlib������������������������������������������������� 169


Visualizing a Function as an Image and a Contour������������������������������������������������������������������� 169
3D Vignettes������������������������������������������������������������������������������������������������������������������������������ 171
Decorated Scatter Plots������������������������������������������������������������������������������������������������������������ 172
Time Plots and Signals�������������������������������������������������������������������������������������������������������������� 173
Filled Plots�������������������������������������������������������������������������������������������������������������������������������� 175
Step Plots���������������������������������������������������������������������������������������������������������������������������������� 176
Hexbins������������������������������������������������������������������������������������������������������������������������������������� 178
XKCD Style�������������������������������������������������������������������������������������������������������������������������������� 178
Summary���������������������������������������������������������������������������������������������������������������������������������� 180

Chapter 14: Introduction to Pandas���������������������������������������������������������������������� 181


Introduction to Pandas�������������������������������������������������������������������������������������������������������������� 181
Series in Pandas������������������������������������������������������������������������������������������������������������������ 182
Basic Operations on Series������������������������������������������������������������������������������������������������� 184
Dataframe in Pandas����������������������������������������������������������������������������������������������������������������� 185
Summary���������������������������������������������������������������������������������������������������������������������������������� 190

Chapter 15: Data Acquisition�������������������������������������������������������������������������������� 191


Plain-Text File Handling������������������������������������������������������������������������������������������������������������ 192
Handling CSV Files with Python������������������������������������������������������������������������������������������������ 194
Python and Excel����������������������������������������������������������������������������������������������������������������������� 196

viii
Table of Contents

Writing and Reading Files with NumPy������������������������������������������������������������������������������������� 198


Reading the Data from a CSV File with NumPy������������������������������������������������������������������������� 199
Matplotlib CBook����������������������������������������������������������������������������������������������������������������������� 200
Reading Data from a CSV���������������������������������������������������������������������������������������������������������� 201
Reading Data from an Excel File����������������������������������������������������������������������������������������������� 202
Reading Data from JSON���������������������������������������������������������������������������������������������������������� 203
Reading Data from a Pickle File������������������������������������������������������������������������������������������������ 204
Reading Data from the Web������������������������������������������������������������������������������������������������������ 204
Interacting with the Web API����������������������������������������������������������������������������������������������� 205
Reading Data from a Relational Database Table����������������������������������������������������������������������� 207
Reading Data from the Clipboard���������������������������������������������������������������������������������������������� 208
Summary���������������������������������������������������������������������������������������������������������������������������������� 209

Chapter 16: Visualizing Data with Pandas and Matplotlib����������������������������������� 211


Simple Plots������������������������������������������������������������������������������������������������������������������������������ 212
Bar Graphs�������������������������������������������������������������������������������������������������������������������������������� 213
Histograms�������������������������������������������������������������������������������������������������������������������������������� 218
Box Plots����������������������������������������������������������������������������������������������������������������������������������� 222
Area Plots���������������������������������������������������������������������������������������������������������������������������������� 230
Scatter Plots������������������������������������������������������������������������������������������������������������������������������ 232
Hexagonal Bin Plots������������������������������������������������������������������������������������������������������������������ 236
Pie Charts���������������������������������������������������������������������������������������������������������������������������������� 237
Summary���������������������������������������������������������������������������������������������������������������������������������� 241

Chapter 17: Introduction to Data Visualization with Seaborn������������������������������ 243


What Is Seaborn?���������������������������������������������������������������������������������������������������������������������� 243
Plotting Statistical Relationships���������������������������������������������������������������������������������������������� 245
Plotting Lines���������������������������������������������������������������������������������������������������������������������������� 251
Visualizing the Distribution of Data������������������������������������������������������������������������������������������� 252
Summary���������������������������������������������������������������������������������������������������������������������������������� 267

ix
Table of Contents

Chapter 18: Visualizing Real-Life Data with Matplotlib and Seaborn������������������� 269
COVID-19 Pandemic Data���������������������������������������������������������������������������������������������������������� 269
Fetching the Pandemic Data Programmatically������������������������������������������������������������������������ 271
Preparing the Data for Visualization������������������������������������������������������������������������������������������ 275
Creating Visualizations with Matplotlib and Seaborn���������������������������������������������������������������� 276
Creating Visualizations of Animal Disease Data������������������������������������������������������������������������ 287
Summary���������������������������������������������������������������������������������������������������������������������������������� 292

Index��������������������������������������������������������������������������������������������������������������������� 293

x
About the Author
Ashwin Pajankar earned a Master of Technology in computer science engineering from
IIIT Hyderabad and has more than 25 years of experience in the area of programming.
He started his journey in programming and electronics at the tender age of 7 with the
BASIC programming language and is now proficient in Assembly programming, C, C++,
Java, shell scripting, and Python. His other technical expertise includes single-board
computers such as the Raspberry Pi and Banana Pro, microcontroller boards such as the
Arduino, and embedded boards such as the BBC Micro Bit.
He is currently a freelance online instructor teaching programming to more
than 70,000 professionals. He also regularly conducts live programming bootcamps
for software professionals. His growing YouTube channel has an audience of more
than 10,000 subscribers. He has published more than 15 books on programming and
electronics.
In addition to his technology work, he volunteers for many social causes. He has
won several awards at his university and past workplaces for his community service.
He has also participated in many industry–institute linkage programs, connecting his
past employers with his alma maters. During the COVID-19 pandemic (which was
unfolding at the time of writing of this book), he participated in and led many initiatives
to distribute essential supplies and medicine to needy people in his local community.

xi
About the Technical Reviewer
Joos Korstanje is a data scientist with more five years of industry experience in
developing machine learning tools, especially forecasting models. He currently works
at Disneyland Paris where he develops machine learning for a variety of tools. He is the
author of the book Advanced Forecasting with Python.

xiii
Acknowledgments
I would like to thank Celestin and Aditee for giving me an opportunity to share my
knowledge and experience with readers. I thank James Markham for helping me to
shape this book according to Apress standards. I am in debt to the technical reviewer for
helping me to improve this book. I also thank Prof. Govindrajulu Sir’s family, Srinivas
(son) and Amy (daughter in law), for allowing me to dedicate this book to his memory
and for sharing his biographical information and photograph for publication. I would
also like to thank all the people at Apress who were instrumental in bringing this project
to reality.

xv
Introduction
I have been working in the domain of data science for more than a decade now, and I
was introduced to Python more than 15 years ago. When I first worked with libraries
such as NumPy, Matplotlib, and Pandas, I found it a bit tedious to comb through all
the available literature in the form of printed books, video tutorials, and online articles,
as most of them lacked comprehensive steps for beginners. It was then that I resolved
to write a book, and I am glad that I could bring my resolution to life with the help of
Apress.
This book is the result of thousands of hours (in addition to the ones spent writing
the actual book) going through technical documentation, watching training videos,
writing code with the help of different tools, debugging faulty code snippets, posting
questions and participating in discussions on various technical forums, and referring
to various code repositories for pointers. I have written the book in such a way that
beginners will find it easy to understand the topics. The book has hundreds of code
examples and images of code output so that you can fully understand each concept
introduced. All the code examples are explained in detail.
The book begins with a general discussion of Python and a small guide explaining
how to install it on various computing platforms such as the Windows OS and Linux
computers (like the Raspberry Pi). We then move on to discussing the scientific
ecosystem. Then we focus on NumPy, which is the fundamental library for numerical
computing. We specifically focus on the multidimensional, array-like data structure
of NumPy, called the Ndarray. We then explore data visualization libraries, such as
Matplotlib and Plotly, to learn how to plot Ndarrays.
Most of the chapters explore the data visualization library Matplotlib. You will learn a
lot of data visualization tips and techniques in these chapters.
Then we dive into Pandas so you can learn about its important data structures, called
the series and dataframe. Midway through the book, you will also learn how to read data
from various data sources using Python, NumPy, Matplotlib, and Pandas. You will also
learn how to visualize Pandas data with popular visualization libraries such as Matplotlib
and Seaborn, as well as how to work with time-indexed data.

xvii
Introduction

On an ending note, we started and finished working on this project at a very


turbulent time (the beginning of 2021) marked by hardships such as hospitalization and
deaths of friends, social unrest, lockdowns, curfews, economic slowdown, and a host of
other sociopolitical problems brought about in part by the COVID-19 pandemic. I myself
was hospitalized due to severe complications from pneumonia and breathing troubles
caused by a COVID-19 infection. It delayed the launch of this long-planned project. To
be frank, working on this book with the help of my longtime mentors at Apress (Celestin,
James, and Aditee) offered me a sense of purpose in these troubled times. I end this
introduction with a note of hope and positive words that we, as a society and a global
civilization, will overcome these turbulent times with the help of each other, and I look at
the future with a lot of hope and bright eyes.

xviii
CHAPTER 1

Introduction to Python 3
I welcome you all to the exciting journey of data visualization with Matplotlib and related
libraries such as NumPy, Pandas, and Seaborn.
This chapter covers the basics of the Python programming language including its
history, installation, and applications. You will be writing a few simple and introductory
Python 3 programs and be learning how to execute them on various OS platforms.
Then, we will start exploring the scientific Python ecosystem. We will briefly discuss
the member libraries of the scientific Python ecosystem, and toward the end, we will
explore Jupyter Notebook so we can use it throughout the rest of the book.
Specifically, the following are the topics covered in this chapter:

• Python programming language

• Python installation on various platforms

• Python modes

• Python IDEs

• Scientific Python ecosystem


• Overview and setup of Jupyter Notebook

• Running code in Jupyter Notebook

• Anaconda

After reading this chapter, you will be comfortable with the installation and the basic
usage of the Python 3 programming language in various modes on various platforms.

1
© Ashwin Pajankar 2022
A. Pajankar, Hands-on Matplotlib, https://doi.org/10.1007/978-1-4842-7410-1_1
Chapter 1 Introduction to Python 3

Introducing the Python 3 Programming Language


Python 3 is a general-purpose, high-level, and interpreted programming language. In
this section, we will discuss the Python programming language and its philosophy.

History of the Python Programming Language


Python is a successor to the ABC programming language, which itself was inspired by the
ALGOL 68 and SETL programming languages. Python was created by Guido van Rossum
as a side project during vacations in the late 1980s while he was working at Centrum
Wiskunde & Informatica (English: “National Research Institute for Mathematics and
Computer Science”) in the Netherlands. Van Rossum was born and raised in the
Netherlands. He obtained a master’s degree in math and computer science from the
University of Amsterdam. He worked for Google and Dropbox and retired after that.
However, in November 2020, he joined Microsoft.
Since the initial release of the Python programming language till July 2018, Guido
has been the lead developer and benevolent dictator for life (BDFL) for this project. He
worked on the steering committee for Python through 2019, but in 2020, he withdrew his
nomination from reelection to the steering committee.
The following are the important milestones in Python’s release timeline:

• February 1991: Van Rossum published the code (labeled version


0.9.0) to alt.sources.

• January 1994: Version 1.0 was released.


• October 2000: Python 2.0 was released.

• December 2006: Python 3.0 was released.

• December 2019: Python 2.x was officially retired and is no longer


supported by Python Software Foundation.

As you can see, Python 2.x versions are no longer supported, as Python 2 is retired.
Python 3 is not backward compatible with Python 2. Python 3 is the latest and supported
version of the Python programming language. So, we will use Python 3 programming
throughout the book to demonstrate the concepts covered. Unless explicitly mentioned,
Python means Python 3 throughout this book.

2
Chapter 1 Introduction to Python 3

Python Enhancement Proposals


To steer the development, maintenance, and support of Python, the Python leadership
came up with the concept of Python enhancement proposals (PEPs). They are the
primary mechanism for suggesting new features and fixing issues in the Python project.
You can read more about the PEPs at the following URLs:

https://www.python.org/dev/peps/
https://www.python.org/dev/peps/pep-0001/

Philosophy of the Python Programming Language


The philosophy of Python is detailed in PEP20. It is known as the Zen of Python and is at
https://www.python.org/dev/peps/pep-0020/. The following are the points from that
PEP. A few are funny.

• Beautiful is better than ugly.

• Explicit is better than implicit.

• Simple is better than complex.

• Complex is better than complicated.

• Flat is better than nested.

• Sparse is better than dense.

• Readability counts.

• Special cases aren’t special enough to break the rules.

• Although practicality beats purity.

• Errors should never pass silently.

• Unless explicitly silenced.

• In the face of ambiguity, refuse the temptation to guess.

• There should be one—and preferably only one—obvious way to do it.

• Although that way may not be obvious at first unless you’re Dutch.

3
Chapter 1 Introduction to Python 3

• Now is better than never.

• Although never is often better than right now.

• If the implementation is hard to explain, it’s a bad idea.

• If the implementation is easy to explain, it may be a good idea.

• Namespaces are one honking great idea—let’s do more of those!

These are the general philosophical guidelines that continue to influence the
development of the Python programming language.

A
 pplications of Python
As you have learned, Python is a general-purpose programming language; it has
numerous applications in the following areas:

• Web development

• GUI development

• Scientific and numerical computing

• Software development

• System administration

You can read case studies of Python at https://www.python.org/success-stories/.

Installing Python on Various Platforms


A Python implementation is a program (the actual binary executable of the interpreter
of Python) that supports the execution of programs written in the Python programming
language. The original implementation created by Guido van Russom is known as
CPython and serves as the reference implementation. Throughout the book, we will be
using CPython. It is available on the Python website, and you will learn how to install
it on the Windows OS in this section. I prefer to write Python programs on a Windows
computer or a Raspberry Pi computer with the Raspberry Pi OS. You can find the
list of alternative Python implementations at https://www.python.org/download/
alternatives/.

4
Chapter 1 Introduction to Python 3

I think now is a good time to discuss various Python distributions. You saw that
the actual interpreter program for Python is known as an implementation. When it
is bundled with a few useful things such as an integrated development environment
(IDE), tools, and libraries, it is known as a distribution. You can find the list of Python
distributions at https://wiki.python.org/moin/PythonDistributions.
Now, let’s look at how to install Python on both platforms.

Installing on a Windows Computer


Visit the Python 3 download page located at https://www.python.org/downloads/
and download the setup file of Python 3 for your computer. The page will automatically
detect the operating system on your computer and show the appropriate downloadable
file, as shown in Figure 1-1.

Figure 1-1. Python project home page with download options

Run the setup file to install Python 3. During installation, select the check box related
to adding Python 3 to the PATH variable (Figure 1-2).

5
Chapter 1 Introduction to Python 3

Figure 1-2. Python installation wizard

Also, choose the “Customize installation” option. That will take you to more options,
as shown in Figure 1-3.

6
Chapter 1 Introduction to Python 3

Figure 1-3. Python installation options

Select all the boxes and click the Next button to continue the setup. Complete the
setup. The name of the binary executable program for Python is python on Windows.
Once the installation completes, run the following command at the Windows command
prompt, cmd:

python -V

This will return the version of Python 3 as follows:

Python 3.8.1

You can also check the version of pip as follows:

pip3 -V

A recursive acronym, pip stands for “Pip installs Python” or “Pip installs packages.”
It is a package manager for the Python programming language. You can install the other
needed Python libraries for our demonstrations using the pip utility.

7
Chapter 1 Introduction to Python 3

To find out the exact location of Python, you can run the where command as follows:

where python

This returns the following result:

C:\Users\Ashwin\AppData\Local\Programs\Python\Python38-32\python.exe

Similarly, you can find out the location of the pip3 utility by running the following
command:

where pip3

We will be using this utility heavily throughout the book to install and manage
Python 3 libraries on the computer we are working with. The following command lists all
the installed packages:

pip3 list

Installing on Ubuntu/Debian Derivatives


Debian is a popular distribution. Ubuntu Linux and the Raspberry Pi OS are the other
popular distributions based on Debian. Python 3 and pip3 come pre-installed on all the
Debian distributions and derivatives such as Ubuntu or the Raspberry Pi OS. So, we do
not have to install them separately. I use the Raspberry Pi OS on a Raspberry Pi 4B with
8 GB RAM as my Linux computer. Both the major Python versions, Python 2 and Python
3, come preinstalled on all the Debian derivatives. Their executable files for interpreters
are named as python and python3 for Python 2 and Python 3, respectively. We will use
python3 for our demonstrations. To find out the versions and locations of the needed
binary executable files, run the following commands one by one:

python3 -V
pip3 -V
which python3
which pip3

Almost all the other popular Linux distributions come with Python pre-installed too.

8
Chapter 1 Introduction to Python 3

Using Python Modes


The Python programming language has various modes for executing programs (and
statements, as you will see soon). Let’s discuss them one by one. But before we get
started with that discussion, let’s look at what IDLE is. IDLE is an integrated development
and learning environment developed by the Python Software Foundation for Python
programming. When you install the CPython implementation of Python 3 on Windows,
IDLE is also installed. You can launch it on Windows OS in various ways. The first way is
to search for it in the Windows search bar by typing in IDLE, as shown in Figure 1-4.

Figure 1-4. Python IDLE on Windows


9
Chapter 1 Introduction to Python 3

The other way is to launch it from the command prompt (cmd) by running the
following command:

idle

This will launch the window shown in Figure 1-5.

Figure 1-5. Python IDLE

Before proceeding, you need to customize IDLE so that it works for you. You can
change the font by selecting Options ➤ Configure IDLE, as shown in Figure 1-6.

Figure 1-6. Configuring IDLE

The window shown in Figure 1-7 opens so you can change the font and size of the
characters in IDLE.

10
Chapter 1 Introduction to Python 3

Figure 1-7. IDLE configuration window

11
Chapter 1 Introduction to Python 3

Adjust the options according to your own preferences.


All the Linux distributions may not come with IDLE pre-installed. You can install it
on the Debian and derivatives (Ubuntu and Raspberry Pi OS) by running the following
commands in sequence:

sudo apt-get update


sudo apt-get install idle3

Once the installation is complete, you can find IDLE in the menu (in this case the
Raspberry Pi OS menu), as shown in Figure 1-8.

Figure 1-8. IDLE in Raspberry Pi OS menu

You can also launch IDLE on Linux by running the following command:

idle

Now let’s discuss the various modes of Python.

12
Chapter 1 Introduction to Python 3

I nteractive Mode
Python’s interactive mode is like a command-line shell that executes the current
statement and gives immediate feedback on the console. It runs the statements given
to it immediately. As new statements are fed into and executed by the interpreter, the
code is evaluated. When you open IDLE, you will see a command-line prompt. This is
Python’s interactive mode. To see a simple example, let’s type in the customary Hello
World program in the interactive prompt as follows:

print('Hello World!')

Press the Enter key to feed the line to the interpreter and execute it. Figure 1-9 shows
the output.

Figure 1-9. Python interactive mode on IDLE

You can launch Python’s interactive mode from the command prompt too. At
the Linux command prompt (e.g., lxterminal), run the command python3, and at the
Windows command prompt (cmd), run the command python. Figure 1-10 shows the
interactive mode at the Windows command prompt.

13
Chapter 1 Introduction to Python 3

Figure 1-10. Python interactive mode, Windows command prompt

Script Mode
You can write a Python program and save it to disk. Then you can launch it in multiple
ways. This is known as script mode. Let’s demonstrate it in IDLE. You can use any text
editor to write the Python program. But as IDLE is an IDE, it is convenient to write and
run the Python programs using IDLE. Let’s see that first. In IDLE, select File ➤ New File.
This will create a new blank file. Add the following code to it:

print('Hello World!')

Then save it with the name prog01.py on the disk (Figure 1-11).

Figure 1-11. A Python program in the IDLE code editor

In the menu, select Run ➤ Run Module. This will execute the program at IDLE’s
prompt, as shown in Figure 1-12.

14
Chapter 1 Introduction to Python 3

Figure 1-12. A Python program under execution at the IDLE prompt

You can even launch the program with Python’s interpreter at the command prompt
of the OS. Open the command prompt of the OS and navigate to the directory where the
program is stored. At the Windows command prompt, run the following command:

python prog01.py

In the Linux terminal, you must run the following command prompt:

python3 prog01.py

Then the interpreter will run the program at the command prompt, and the output
(if any) will appear there.
In Linux, there is another way you can run the program without explicitly using the
interpreter. You can add a shebang line to the beginning of the code file. For example, say
our code file looks like this:

#!/usr/bin/python3
print('Hello World!')

The first line is known as a shebang line. It tells the shell what interpreter to use and
its location. Then run the following command to change the file permission to make it
executable for the owner as follows:

chmod 755 prog01.py

Then you can directly launch your Python program file like any other executable
with ./, as follows:

./prog01.py

15
Chapter 1 Introduction to Python 3

The shell will execute the program and print the output in the terminal. Note
that this is applicable only for Unix-like systems (Linux and macOS) as they support
executing programs like this. You will learn more about Python programming
throughout the book.

Using Python IDEs


You have learned how to work with the Python interpreter and IDLE to run Python 3
statements and programs. You can use other freely available IDEs and plugins for IDEs to
work with Python. The following is a list of a few famous IDEs and plugins for Python 3
along with the URLs to their home pages:

• PyCharm Community Edition (https://www.jetbrains.com/


pycharm/)

• Spyder IDE (https://www.spyder-ide.org/)

• Thonny Python Editor (https://thonny.org/)

• Mu Editor (https://codewith.mu/)

• PyDev plugin for Eclipse (https://www.pydev.org/)

All these IDEs and plugins are free to download and use. As an exercise for this
chapter, you may want to explore them to find the IDE you are most comfortable with.

Exploring the Scientific Python Ecosystem


The scientific Python ecosystem is a collection of open source Python libraries for
scientific computing. It has the following core components:

• Python: This is a programming language.

• NumPy: This is the fundamental library for numerical computation.


Almost all the libraries in the scientific Python ecosystem are based
on NumPy. It provides a versatile data structure known as an Ndarray
(for “N-dimensional array”).

16
Chapter 1 Introduction to Python 3

• SciPy: This library has many routines for scientific computations.

• Matplotlib: This is a library for visualization. Its pyplot module has


routines for Matlab-style visualizations.

Together, all these components provide functionality like Matlab:

Pandas: This is a library for data science and provides high-


performance, easy-to-use data structures like the series and
dataframes for storing data.

SymPy: This is for symbolic mathematics and algebra.

NetworkX: This is a library for representing and visualizing graphs


and networks.

Scikit-image: This is a library for image processing.

Scikit-learn: This is a library for machine learning and artificial


intelligence.

In addition to these libraries, IPython provides a better interactive environment for


the Python interpreter. IPython’s interactive environment can be accessed through web-
based notebooks using Jupyter Notebook.
The rest of the chapter focuses on Jupyter Notebook.

Introducing Jupyter Notebook


Earlier in this chapter, you learned various ways to run Python statements. You ran
Python statements in a script and in the interpreter’s interactive mode. The main
advantage of using interactive mode is the immediate feedback. The main disadvantage
of this mode is that if you make any mistakes in the statements you’re typing in, you
must write the entire statement again to re-execute it. Also, it is difficult to save it as a
program. The option for saving the statements to run on the interpreter can be found in
the File option of the menu. However, all the statements and their outputs will be saved
in plain-text format with the .py extension. If there is any graphical output, it is displayed
separately and cannot be stored with the statements.
Because of the limitations of interactive mode in the interpreter, we will use a better
tool for running the Python statements interactively in the web browser. The tool is

17
Chapter 1 Introduction to Python 3

known as Jupyter Notebook. It is a server program that can create interactive notebooks
in a web browser.
Jupyter Notebook is a web-based notebook that is used for interactive programming
of various programming languages like Python, Octave, Julia, and R. It is popular
with people who are working in research domains. Jupyter Notebook can save code,
visualizations, output, and rich text in a single file. The advantage of Jupyter Notebook
over Python’s own interactive prompt is that you can edit the code and see the new
output instantly, which is not possible in Python’s interactive mode. Another advantage
is that you have the code, rich-text elements, and output of the code (which can be in
graphical or rich-text format) in the same file on disk. This makes it easy to distribute.
You can save and share these notebooks over the Internet or using the portable storage
equipment. There are many services online that help to store and execute your notebook
scripts on cloud servers.

Setting Up Jupyter Notebook


You can easily install the Jupyter Notebook server program on any computer by running
the following command at the command prompt:

pip3 install jupyter

Let’s see how you can use Jupyter Notebook for writing and executing Python
statements now. Run the following command in the command prompt of the OS to
launch the Jupyter Notebook server process there:

jupyter notebook

The Jupyter Notebook server process will be launched, and the command prompt
window shows a server log, as in Figure 1-13.

18
Chapter 1 Introduction to Python 3

Figure 1-13. Launching a new Jupyter Notebook process

Also, it launches a web page in the default browser of the OS. If the browser window
is already open, then it launches the page in a new tab of the same browser window.
Another way to open the page (in case you close this browser window running Jupyter
Notebook) is to visit http://localhost:8888/ in your browser. It displays the page
shown in Figure 1-14.

19
Chapter 1 Introduction to Python 3

Figure 1-14. Logging in with a token

The following lines of text are the server logs.

To access the notebook, open this file in a browser:

file:///C:/Users/Ashwin/AppData/Roaming/jupyter/runtime/nbserver-8420-open.html

Or copy and paste one of these URLs:

http://localhost:8888/?token=e4a4fab0d8c22cd01b6530d5daced19d32d7e0c3a56f925c
http://127.0.0.1:8888/?token=e4a4fab0d8c22cd01b6530d5daced19d32d7e0c3a56f925c

In the previous log, you can see a couple of URLs. They refer to the same
page (localhost and 127.0.0.1 are the same hosts). Either you can directly copy
and paste any of these URLs directly in the address bar of the browser tab and
open the Jupyter Notebook home page or you can visit http://localhost:8888/
as discussed earlier and then paste the token in the server log (in our case it is
e4a4fab0d8c22cd01b6530d5daced19d32d7e0c3a56f925c) and log in. This will take you
to the same home page.

20
Chapter 1 Introduction to Python 3

Note that every instance of the Jupyter Notebook server will have its own token, so
the token shown in the book will not work with your notebook. The token is valid only
for that server process.
So, if you follow any one of the routes explained earlier, you will see a home page tab
in the browser window, as shown in Figure 1-15.

Figure 1-15. A new home page tab of Jupyter Notebook

As you can see, there are three tabs on the web page: Files, Running, and Clusters.
The Files tab shows the directories and files in the directory from where you launched
the notebook server from the command prompt. In the previous example, I executed
the command jupyter notebook from lxterminal of my Raspberry Pi. And the current
working directory is the home directory of the pi user /home/pi. That is why you can
see all the files and directories in the home directory of my Raspberry Pi computer in
Figure 1-15.
In the top-right corner, you can see the Quit and Logout buttons. If you click the
Logout button, then it logs out from the current session, and to log in, you again need
the token or URL with the embedded token from the notebook server log, as discussed
earlier. If you click the Quit button, then it stops the notebook server process running at
the command prompt and displays the modal message box shown in Figure 1-16.

21
Chapter 1 Introduction to Python 3

Figure 1-16. The message shown after clicking the Quit button

To work with the Jupyter Notebook, you need to execute the command jupyter
notebook again at the command prompt.
On the top-right side, just below the Quit and Logout buttons, you can see a small
button with a refresh symbol. This button refreshes the home page. You also have the
New button. Once clicked, it shows a drop-down, as shown in Figure 1-17.

Figure 1-17. Options for a new notebook

As you can see, the drop-down is divided into two sections, Notebook and Other. You
can create the Octave and Python 3 notebooks. If your computer has more programming
languages installed that are supported by Jupyter Notebook, then all those languages
will show up here. You can also create text files and folders. You can open a command
prompt in the web browser by clicking Terminal. Figure 1-18 shows lxterminal running
in a separate web browser tab.

22
Chapter 1 Introduction to Python 3

Figure 1-18. A new lxterminal window within the browser

Clicking Python 3 in the drop-down creates a new Python 3 notebook, as shown in


Figure 1-19.

Figure 1-19. A new Python 3 notebook

23
Chapter 1 Introduction to Python 3

If you go to the home page again by clicking the home page tab in the browser and
then open the Running tab in the home page, you can see the entries corresponding to
the terminal and the Python 3 notebook, as shown in Figure 1-20.

Figure 1-20. Summary of current Jupyter Notebook subprocesses

Running Code in Jupyter Notebook


Go to Python 3’s Untitled1 tab again and type in the following statement in the text area
(also known as a cell):

printf("Hello, World!\n");

Then click the Run button. Jupyter will execute the statement as a Python 3
statement and show the result immediately below the cell, as shown in Figure 1-21.

Figure 1-21. Code output in Jupyter Notebook


24
Chapter 1 Introduction to Python 3

As you can see, after execution, it automatically creates a new cell below the
result and sets the cursor there. Let’s discuss the menu bar and the icons above the
programming cells. You can save the file by clicking the floppy disk icon. You can add a
new empty cell after the current cell by clicking the + icon. The next three icons are Cut,
Copy, and Paste. Using the up and down arrows can shift the position of the current cell
up and down, respectively. The next option is to run the cell, which you already saw. The
next three icons are for interrupting the kernel, restarting the kernel, and rerunning all
the cells in the notebook. Next to that, you have a drop-down that tells you what type of
cell it should be. Figure 1-22 shows the drop-down when clicked.

Figure 1-22. Types of cells in Jupyter Notebook

The cell is treated as a Python 3 code cell when you choose the Code option. It is
treated as a Markdown cell when you choose the Markdown option. Markdown is a
markup language that can create rich-text output. For example, anything followed by #
creates a heading, anything followed by ## creates a subheading, and so on. Just type the
following lines in a Markdown cell and execute them:

# Heading 1
## Heading 2

During our Python 3 demonstrations, we will mostly use Markdown for headings.
However, you can further explore Markdown on your own by visiting https://jupyter-
notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20
Markdown%20Cells.html. Figure 1-23 shows the output of the previous demonstration.

25
Chapter 1 Introduction to Python 3

Figure 1-23. Headings in Markdown

You can even change the name of the notebook file by clicking its name in the top
part of the notebook. Once you click, you’ll see a modal box for renaming, as shown in
Figure 1-24.

Figure 1-24. Renaming a notebook in Jupyter

Rename the notebook if you want. If you browse the location on disk from where you
launched the Jupyter Notebook from at the command prompt, you will find the file with
the .ipynb extension (meaning “IPython notebook”).
In the same way, you can use Jupyter Notebook for doing interactive programming
with the other programming languages that support Jupyter. We will mostly use this
notebook format to store our code snippets for interactive sessions. This is because
everything is saved in a single file that can be shared easily, as discussed earlier.

26
Chapter 1 Introduction to Python 3

You can clear the output of a cell or the entire notebook. In the menu bar, click the
Cell menu. In the drop-down, Current Outputs and All Output have a Clear option that
clears the output of cells. Figure 1-25 shows the options.

Figure 1-25. Clearing the output in Jupyter

One of the most significant advantages of Jupyter Notebook is that you can edit an
already executed cell if there is any syntax error or you simply want to change the code.
Jupyter Notebook is like an IDE that runs within a web browser and produces the output
in the same window. This interactivity and facility to keep code, rich text, and output in
the same file has made Jupyter Notebook project hugely popular worldwide. The kernel
for running Python programs comes from the IPython project. As I mentioned earlier,
you can use it for other programming languages too. I have used it for running GNU
Octave programs.
You can find more information about Jupyter Notebook and IPython at the
following URLs:

https://jupyter.org/
https://ipython.org/

27
Chapter 1 Introduction to Python 3

A
 naconda
Before we can conclude the chapter, we need to discuss the Python distributions. A
Python distribution is nothing more than the Python interpreter bundled with Python
libraries. One such popular distribution is Anaconda. You can download and install
Anaconda on Linux, Windows, and macOS. Anaconda has many versions. One of them
is free and meant for individual usage. You can find it at https://www.anaconda.com/
products/individual.
Anaconda comes with an open source package manager that can install packages for
Python and other programs. It is known as Conda. You can find more information about
the Conda package manager at https://docs.conda.io/en/latest/.
If you have already installed Python from Python’s website, I recommend using
another computer to install Anaconda. Having multiple interpreters and distributions of
Python can be confusing.

S
 ummary
In this chapter, you learned the basics of Python programming language. You learned
how to write basic Python programs and how to execute them in various ways. You
learned to work with Python on various operating systems such as Windows and Linux.
You also learned various modes of the Python programming language and how to launch
Python from the command prompts of various operating systems. You learned the basics
of the built-in package manager of Python, called pip. We also briefly discussed other
IDEs for Python.
Then, you got a brief introduction to the scientific Python ecosystem. We will explore
many components of this ecosystem in the coming chapters. You also learned how to
install Jupyter Notebook on various platforms and explored how you can run simple
Python statements in Jupyter Notebook. You learned that you can store the code and the
output of the same code in a single file that can be shared easily over the Internet and
other media such as portable storage devices.
In the next chapter, we will get started with NumPy.

28
CHAPTER 2

Getting Started with NumPy


In the previous chapter, you learned the basics of the Python programming language and
the scientific Python ecosystem. You also learned how to run simple Python programs in
interactive web-based notebooks with Jupyter. We will continue using Jupyter Notebook
for the majority of demonstrations in the rest of the chapters in the book.
In this chapter, we will give a brief overview of the NumPy library with a few coding
demonstrations. The following is the list of topics that we will explore in this chapter:

• Introduction to the NumPy Ndarrays

• Ndarray properties

• NumPy constants

Throughout the remaining chapters of this book, we will explore many components
of the scientific Python ecosystem one by one. Throughout this book, we will be
using different libraries that are part of this scientific Python ecosystem. The valuable
knowledge you will gain in this chapter serves as a foundation for the rest of the chapters.
As this is an introductory chapter for a broad ecosystem, I have kept it short yet practical.

N
 umPy and Ndarrays
NumPy is the fundamental package for numerical computation in Python. We can
use it for numerical computations. The most useful feature of the NumPy library is the
multidimensional container data structure known as an Ndarray.
An Ndarray is a multidimensional array (also known as a container) of items that
have the same datatype and size. We can define the size and datatype of the items at the
time of creating the Ndarray. Just like other data structures such as lists, we can access
the contents of an Ndarray with an index. The index in an Ndarray starts at 0 (just like
arrays in C or lists in Python). We can use Ndarrays for a variety of computations. All the

29
© Ashwin Pajankar 2022
A. Pajankar, Hands-on Matplotlib, https://doi.org/10.1007/978-1-4842-7410-1_2
Chapter 2 Getting Started with NumPy

other libraries in the scientific Python ecosystem recognize and utilize NumPy Ndarrays
and associated routines to represent their own data structures and operations on them.
Let’s get started with the hands-on material. Create a new notebook for this chapter.
Run the following command to install the NumPy library on your computer:

!pip3 install numpy

Let’s import it to the current notebook by running the following command:

import numpy as np

You can create a list and use it to create a simple Ndarray as follows:

l1 = [1, 2, 3]
x = np.array(l1, dtype=np.int16)

Here you are creating an Ndarray from a list. The datatype of the members is a 16-bit
integer. You can find the detailed list of datatypes supported at https://numpy.org/
devdocs/user/basics.types.html.
You can write the previous code in a single line as follows:

x = np.array([1, 2, 3], dtype=np.int16)

Let’s print the value of the Ndarray and its type (which, we know, is an Ndarray).

print(x)
print(type(x))

The output is as follows:

[1 2 3]
<class 'numpy.ndarray'>

As you can observe in the previous output, it is of the class numpy.ndarray.


You can also use Python’s interactive mode for running all the statements, as shown
in Figure 2-1.

30
Other documents randomly have
different content
Mr. Clegg: Supposing that at the trial this man is not defended—​a
state of things which is not at all unlikely.
The Stipendiary: You know very well that in that case the judge
would order some learned counsel to defend the prisoner. I am not
going to deal with a state of circumstances that may arise at the
trial. It would be presumption in me to provide for want of justice
before the judges.
Mr. Clegg: This is a preliminary inquiry, and I can put in whatever
I think is for the benefit of the prisoner. Though it is only a
preliminary inquiry I am bound to do it.
The Stipendiary: I rule that sufficient has been asked about those
lettters.
Mr. Clegg: I shall persist in asking these questions until I am
stopped.
The Stipendiary: Then I stop them now. You have quite enough
for your purpose.
Mr. Clegg: I don’t think I have.
The Stipendiary: You have quite enough. You can prosecute her
for perjury if she has spoken falsely as to what has been asked of
her. There are two very particular points, on which she has decisively
spoken in reference to these letters.
Prisoner: She has done more than that.
The Stipendiary: You may if you have cause, indict her for
perjury; it can lead to nothing else.
Mr. Clegg: Then at present I don’t think I have got sufficient, in
my opinion, to test this witness’s credibility.
The Stipendiary: In my opinion, you have. If what you have
asserted is shown to be true, you have more than sufficient to
damage her credibility, and more than sufficient to have a cause for
indicting her for perjury. Beyond that it is not necessary for you to
go, and I rule you shall not go.
Mr. Clegg: How can I indict the woman for perjury unless I put
the letters in her hands?
The Stipendiary: She has looked at them, because I told her to
look at them myself. I said to her, “Look at each one, and see if it is
not in your handwriting.” That is in itself sufficient.
Mr. Clegg: Those letters have been already produced by the
prosecution. I have the right to call for those to be read, and if you
will not now let me cross-examine her in reference to them in detail,
then I ask that the letters be read; then I can cross-examine upon
them, and that comes to the same thing.
The Stipendiary: You should have done that before. It is too late
now. I cannot have them read now.
Mr. Clegg: Put that decision on the depositions. I ask that those
letters put in by the prosecution be read by the clerk of the court.
The Stipendiary: You have seen them.
Mr. Clegg: I have not seen them. I have not had the opportunity
of reading these original letters. By mere favour I have had copies of
them sent to me.
Prisoner: It is nothing but injustice.
The Stipendiary: You will take the ruling of the Court, Mr. Clegg, if
you please, and have done with it.
Mr. Clegg: I put it to you as a matter of law.
The Stipendiary: I have given my decision.
Mr. Clegg: I object to proceed until these letters are read.
Prisoner: Hear, hear.
The Stipendiary: You can proceed with your cross-examination.
Mr. Clegg: I have a right to have the letters read if I please.
The Stipendiary: You can read them over yourself if you like.
Mr. Clegg: If they are put into my hands I shall read them to
witness.
The Stipendiary: Then you may read them.
Mr. Clegg: Very well, then; that is all I want. The witness has
denied that she has had anything to do with them. (To witness):
Have you read them?—​Some of them.
Have you read them all?—​Not all of them.
Then I will read them to you.
Mr. Pollard: There will be no necessity for their being read aloud.
Let the witness read them for herself.
Mr. Clegg: I will read this one to you now, if you please.
(Reading): “If you have a note for me send now whilst he is out, but
you must not venture, for he is watching, and you cannot be too
careful. Hope your foot is better. I went to Sheffield yesterday, but I
could not see you anywhere. Were you out? Love to Jane.” Did you
write that letter?—​No.
Mr. Clegg: Now I put that letter in. Have you had an envelope in
your possession like that (handing an envelope to the witness)?—​I
don’t know; perhaps I might have. As regards the envelope, the
prisoner used to come for paper and writing materials to my house.
Prisoner: No, I did not; oh, no.
Mr. Clegg (holding a yellow envelope in his hand): Have you read
the contents of this?—​Yes, excepting something I could not make
out.
Will you swear that is not your handwriting?—​I swear there are
none of them in my writing.
Mr. Pollard: I think you need hardly put it to her now, because she
has sworn over and over again that there are none of them in her
writing.
Mr. Clegg (to witness): Did you ever give the prisoner an
American cent?—​No.
Did you ever borrow any money from him?—​No.
Not at all?—​I never did.
Mr. Clegg, reading: “Things are looking very bad, for people told
him everything. (Then there is something missing.) Pick out F. D.” Do
you know what that means?—​No.
Mr. Clegg (again reading): “Do keep quiet, and don’t let any one
see you.” You did not write that? No; I did not write that.
The Stipendiary: She says she didn’t write these letters.
Mr. Clegg: Well, I wish to question her on the point.
The Stipendiary: I will not have it, and I will have my ruling
attended to. It shall not go down on the depositions.
Cross-examination continued: You had a son named Willie?—​
William Henry.
How old is he?—​Seven years old last December.
Did the prisoner ever give your son any halfpennies or coppers
that you know of?—​No, not that I am aware of.
You have seen that letter as well (handing a letter to witness)?—​
Yes, I have seen them all.
Do you know a woman named Norton?—​Norton! I seem to
remember the name. I think I remember the name.
Did you ever write this to the prisoner, “Mrs. Norton is raising h
—— about what I——(then follows a blank)——. Can you settle it,
and send me the prints?”
Mr. Pollard: Witness denied that she ever wrote the letter, and the
magistrate has given a ruling.
Mr. Clegg (to witness): When you were before the magistrates
last week you said that you left Darnall in consequence of the
prisoner annoying you?—​Yes, on account of his annoyance.
Had you seen him from July, 1876 up to the time when you left in
October?—​No.
Did you know where he was?—​No, I did not. He made himself
scarce on account of the warrant I had taken out against him.
Did his family leave the neighbourhood before you left?—​I don’t
know.
What do you now say was the reason for your leaving Darnall?
Because we were afraid of him. That was the reason. We thought he
might come in in the night. We thought we had better go where he
would not know where to find us.
It was because you were afraid of him?—​Yes; he had threatened
both my life and that of my husband.
Was the sole reason you left because you were afraid of him?—​
Yes; and we were told that he visited Darnall in female attire.
Did you say that the prisoner had threatened to blow your brains
out, and those of your husband?—​Yes; I said that.
Will you say that he threatened to blow your husband’s brains
out?—​Yes; I will swear that threatened to blow out both my brains
and my husband’s.
Did you state that before the coroner?—​The case was not brought
before the coroner.
Were you not examined before the coroner?—​Yes; on the case of
murder, nothing more.
Were you examined as to the death of your husband?—​Yes.
Did you say then that the prisoner had threatened your life at all?
—​Not that I remember.
The depositions of the witness were then put in by Mr. Pollard,
from which it appeared that before the coroner witness had said that
Peace had threatened to blow out both her brains and her
husband’s.
Had there been any quarrel between prisoner and your husband?
—​I say he had been very annoying.
Was there any quarrel?—​I can’t say there was any quarrel,
because my husband would not speak to him.
Have you ever received a letter from the prisoner at all?—​No sir.
Oh! yes. I have received threatening letters.
Have you got them?—​Mr. Chambers has them, I think.
I am now talking about the night of the murder. Previous to your
going into the closet had your son been taken to bed, do you know?
—​Yes.
Did you see the prisoner when you were in the bedroom?—​No.
When you were coming out of the closet did you see the
prisoner?—​Yes, I did.
Did you say to him, “You old devil, what are you doing here
now?”—​I don’t remember saying anything to him, but he said,
“Speak or I’ll fire.”
Will you swear that you did not say, “You old devil, what are you
doing here to-night? I should have thought that you had brought
enough disgrace upon me?—​I don’ remember speaking at all. I was
too astonished.
Did he say to you, “I will let you have the notes back again if you
will get him to stay proceedings?”—​No.
Did you say, “You know very well he won’t do it, as he has placed
it in the hands of the lawyers?”—​No; I did not speak to him.
Your husband then came up?—​Yes.
How far was he from you and the prisoner before you first saw
him?—​About two or three feet.
How far is the passage from where you were to the closet? Close
by.
Well, how many yards?—​I can’t say.
How far were you from the closet door when you saw your
husband?—​Only three or four feet; I was just at the end.
Whereabouts was the prisoner when he came up?—​The prisoner
was going down the passage.
Was he walking or running away?—​He was going at a rather quick
pace.
Was he walking pretty quickly away from your husband?—​He was
going down the passage.
Away from your husband?—​Away from him.
When your husband was going towards the prisoner did you hear
him say, “If you don’t stop I’ll fire?”—​No.
Did you see the prisoner on the ground?—​How do you mean?
With your husband. Was there any struggling between your
husband and the prisoner?—​No, no.
How far were you away from them when your husband was shot,
did you say?—​A few feet off.
Did you hear the prisoner speak to your husband before he fired?
—​No, I did not. There was no speaking at all.
Not from the time that he came out right up to the time he was
shot?—​No.
Will you swear that your husband and the prisoner were not
struggling together on the ground?—​No, they were not struggling.
They were not close enough together.
Mr. Clegg: What became of the lantern that you had?—​What
became of my lantern?
Yes, had you it in your hand?—​I threw it down.
Before you saw your husband come out had you the lantern still
in your hand?—​Yes.
This concluded the cross-examination of Mrs. Dyson.
Mr. Pollard (re-examining): Are there some steps coming from the
passage into the roadway?—​There are one or two steps.
When your husband fell in what direction did his head fall?—​From
the side of the passage.
Did he take any step forward after the bullet struck him?—​No, he
dropped instantly.
At the time the bullet was fired did you see whether Peace was
down on the pathway of the causeway?—​Yes.
Therefore he would be some few feet below your husband?—​Yes.
He was down off the steps on the causeway when he fired the
second shot.
And you say he would therefore be some two or three feet below
your husband’s head at the time he fired?—​Yes.
You were saying something about threatening letters. Between
July and October, 1876, did you see any threatening letters?—​Yes.
How many?—​I know of two, and there were perhaps more.
Have you those letters?—​Mr. Chambers, solicitor, has them. Mr.
Dyson gave them to Mr. Chambers.
You gave them to Mr. Dyson, your husband, and he gave them to
Mr. Chambere?—​Yes.
You don’t know whose writing they were?—​They were signed as if
from prisoner, and seemed to come from Germany.
(Prisoner: I wish to call witnesses.)
The Stipendiary: It’s not time to call witnesses.
Prisoner: Am I going to be committed to-day? I want my
witnesses called before.
The Stipendiary: It’s not the time.
This concluded Mrs. Dyson’s evidence, who then retired.
Police-constable 235, John Pearson, was next called and
examined by Mr. Pollard. Do you know the prisoner?—​I do, three or
four years.
Prisoner: Let that person come up here, will you? I don’t know
him.
Mr. Pollard (to witness): Three or four years from now?—​Yes, I
knew him about two years before the murder.
You remember the date of the murder of Mr. Dyson in November,
1876?—​Yes.
Did you receive some instructions from your superior officer to go
in search of the prisoner?—​I did. I received instructions the same
morning at half past two o’clock.
That was Nov. 30?—​Yes.
Did you go to any place in Hull which you had any reason to
know?—​Yes, I went to 37, Collier-street.
Who was living there?—​Peace’s wife, I believe. The same person
who had been locked up here in the name of Hannah Peace. She
was keeping a shop.
You failed to find him there?—​Yes.
Mr. Pollard: I propose now to take the escape and recapture of
the prisoner on the last occasion.
Stipendiary: You have gone after the time.
Mr. Pollard: I put it on the ground of what it is worth, as an
element for a jury to consider, whether an innocent person after
having been examined, and hearing evidence such as was given on
the last occasion, would have attempted to escape as he did.
The Stipendiary: He was a convict, you know, suffering under
sentence of penal servitude for life.
Mr. Pollard: Well, I will not press it.
Mr. Pollard then said that was his case.
Prisoner here exclaimed: “I want my witnesses called. Why don’t
you call my witnesses?” and then fell down.
The depositions were now read over, Mrs. Dyson’s being taken
first.
Whilst her depositions were being read the prisoner conducted
himself in an excited and somewhat insolent manner. Making a faint
of jumping from his chair, he fell back suddenly, calling to be taken
to his cell. The warders stepped forward, and he then refused to be
removed, and called for his counsel, to whom he began to give
instructions in an excited fashion. Mr. Clegg took little notice, and
soon after Peace put his arms on the table, laid his head between
them, and moaned loudly. He next drew the rug over his head, and
made such interruptions that the rug was drawn back, and he was
asked to be still. He paid little attention to this request, but kept
moaning and muttering till the deposition were read over.
Stipendiary (to Peace): Do you hear what is said?
Prisoner (whining): Oh yes, I hear.
The depositions were afterwards read over of Sarah Ann
Colgrave, Mary Ann Gregory, George Brassington, Thomas Wilson,
Police-constable Ward, Inspector Bradbury, and Police-constable
Pearson.
Prisoner: Cannot you call my witnesses? What is the use of my
having witnesses if they are not called?
The Stipendiary: Listen to me.
Prisoner: I cannot have them called.
The Stipendiary: Oh, yes, you can, Listen to me. You first of all
have to make a statement, and then if there are any witnesses to be
called they can be called. Now listen to me. The charge against you
is that you wilfully and of malice aforethought did kill and murder
one Arthur Dyson, on Oct. 29, 1876. Having heard the evidence, do
you wish to say anything in answer to the charge?
Prisoner: Yes; I wish to say that——
Stipendiary: You are not obliged to say anything in answer to the
charge. What you do say will be taken down, and may be given in
evidence against you.
Mr. Clegg: If you take my advice you will simply say not guilty.
The Prisoner: I say I am not guilty, and that justice has not been
done to me so that I can prove I am not guilty. That is what I want.
I want that. I want justice done me. Why don’t they let me call my
witnesses, because you are asking me shall my witnesses be called?
Why should they not be called here? Why? because I have not the
money to pay the expenses.
The Stipendiary: What is it you complain of?
The Prisoner: I want my witnesses called to prove that I have
really not done this.
The Stipendiary: Are there any witnesses to be called?
Prisoner: Yes, sir.
The Stipendiary: Are they here?
Prisoner: Yes, sir.
The Stipendiary: Then you must ask your solicitor.
Mr. Robinson (reading): You say, “I say I am not guilty, and I want
my witnesses called to prove I am not guilty.”
Prisoner: That is what I said. I have lots of witnessses who can
prove that that base, bad, woman has threatened my life, and has
threatened her husband’s life; but I can’t talk to you, I am so bad. I
feel very bad. But she has threatened to take my life often.
The Stipendiary: Is this what you say?
Prisoner: I say I am not guilty, and I say I have not justice done
me to prove I am not guilty, and that I want my witnesses called.
(Loudly.) I say I can prove that I have not threatened her life. She
has threatened her husband’s, and she has pointed pistols and
things at me.
The Stipendiary: Have you any witnesses to-day? You are not
taking your trial to-day. This is only a preliminary examination.
Prisoner: I cannot have those witnesses without I pay for them.
Mr. Clegg: I say I don’t intend calling any witnesses to-day.
The Stipendiary: Do you care to sign your statement? Would you
like to put your name to the statement?
Prisoner: I will try.
Prisoner (to his warder, in a very rough tone of voice): Let me be.
Then, taking up the pen, he said, I cannot see.
Mr. Clegg: Just sign it there.
Prisoner then rested his head on one arm and signed his name
very deliberately, the capital “C” and “P” being particularly well
flourished.
The Stipendiary: You are committed to take your trial on this
charge at the assizes at Leeds.
The Prisoner (with eagerness): When are they?
The Stipendary: They are next week.
Inspector Bradbury was then bound over to prosecute, and the
witnesses to appear at the trial.
The Prisoner: Will you let me sit before the fire a bit before I go?
I am really very bad.
Mr. Clegg: He complains of being cold.
Prisoner: You can put me in irons if you like, but put me near a
fire.
The Chief Constable: The cells are warm enough. It is only in this
corridor that there is so much air.
Mr. Clegg: You will be warm enough in the cell.
Prisoner: I want to see you.
Mr. Clegg: Yes, I will see you.
Prisoner was then removed to the cell, groaning and whining,
apparently overcome by the result of the day’s proceedings.
Mrs. Dyson laboured under suppressed emotion, but bore the
ordeal well. The utmost precautions were taken to keep down
excitement in the town, but popular feeling ran very high.
We have during the progress of this work had occasion to refer in
more than instance to the latitude allowed to counsel on police
examinations. A striking instance of this was made manifest on the
several examinations of the prisoner Webster for the Richmond
murder, and before then, in a lesser degree, perhaps, a similar
instance occurred in the examination of the witnesses brought
forward to give their testimony upon the Bannercross murder.
Peace was a daring and reckless burglar. An adept at disguising
himself in a style that eluded the scrutiny of the police, he set small
value on the vigilance of professional detectives.
The comparative immunity with which he had escaped the
consequences of his iniquity induced him to wax bold in
transgression.
Even to the last there seemed an idea that he might still be able
to baffle justice. Everything a wicked ingenuity could do was done to
discredit the testimony on which he was convicted; but the utmost
license of counsel was unavailing.
We are not disposed to say anything severe about a barrister
struggling with the difficulties Mr. Lockwood was called to combat. In
such circumstances the old adage of “No case—​abuse the plaintiff’s
attorney,” is a sufficient explanation of what might otherwise appear
unseemly.
On the present occasion, however, it was not the attorney, but the
press that got abused. In the recent trial of the directors of the City
of Glasgow Bank, a similar policy was pursued by a prominent and
really able advocate.
But the barrister to whom the defence of Charles Peace was
committed passed beyond the duty of counsel in the denunciation of
newspapers.
It was thus that Mr. Lockwood delivered himself:
“Never in the course of my experience has there been such a cry
raised on the part of those who ought to be most careful of all
others in preserving the liberties of their fellow-men and the
independence of the tribunals of justice. I say that in this respect
these parties have proved false to the great duties entrusted to
them, and have not hesitated to raise a merciless cry for blood for
the sake of the paltry pennies which they have been able to extract
from the public, whom they have tried to gull.”
This charge against the press is false. There had really been no
attempt to stimulate public antipathy against the Bannercross culprit.
In point of fact, a judicious critic might with some show of reason
insinuate that the details of the life of Peace had been placed before
the public in aspects more attractive than just.
The convict was not at all averse to the notoriety which he had
recently achieved. But when his life is carefully scanned from the day
that he first enlisted in the “Devil’s Regiment of the Line” until
sentence of death was passed upon him, it is abundantly evident
that the way of the transgressor was hard.
Charles Peace commenced his criminal career before he was
fourteen. He was not yet fifty, but already there was unambiguous
evidence that premature old age was stealing over him.
Though devoted to crime, Peace never consorted with criminals.
This peculiarity in his career constituted his safety. It is mainly
because the haunts and habits of criminals are known that they are
detected.
The impunity with which, for a very considerable period, Peace
was enabled to commit the Blackheath burglaries arose from the air
of mystery with which he was surrounded.
It must not, however, be assumed that there was anything heroic
in the kind of housebreaking with which he was identified.
Houses in the district that formed the scene of his depredations
afford every facility to the “cracksman.” But the good fortune which
had so often favoured Peace in this region at length deserted him.
A constable whom a revolver could not scare mastered the
burglar.
When he was condemned to penal servitude, it was discovered
that the culprit had been guilty of a more serious crime.
“Information received” enabled the authorities to connect the
Blackheath burglar with the Bannercross murder.
That crime was fast fading from the memory of even those
amongst whom it had been committed, and every hope of arresting
the murderer had been abandoned.
Mr. Dyson’s widow was in America, and Peace, who knew this,
thought himself safe.
But, if “justice steals along with woollen feet, it strikes with iron
hands.”
Mrs. Dyson was brought back from the United States to avenge in
the witness-box the brutality of her tormentor.
Her evidence as to all that transpired on the eventful night that
her husband fell was too minute and circumstantial to be shaken by
even the severest cross-examination.
The line of evidence which counsel was instructed to take only
deepened the infamy of the accused.
Even had it been possible to prove an improper intimacy between
Peace and Mrs. Dyson, that would have done nothing to mitigate the
atrocity of Mr. Dyson’s murder.
A most persistent effort was made by Mr. Lockwood to show that,
previous to the firing of the shot from which Mr. Dyson fell, there
had been a struggle between the murderer and his victim.
On this point, however, the widow’s evidence was decisive. There
was indeed no necessity that Mr. Dyson should close with the culprit.
Moreover, inoffensive people are not usually anxious to fight
ruffians who are armed with “six-shooters.”
When Peace was in a difficulty or in a passion, recourse to
firearms seemed perfectly natural. Society was his legitimate prey,
and in presence of unarmed antagonists the burglar waxed valorous.
Rarely has a more wanton murder been perpetrated than that of Mr.
Dyson.
The only offence of which that unfortunate man appeared guilty
was his abhorrence of the attentions of Peace. To escape them, he
removed from the neighbourhood in which the convict dwelt.
The scamp, however, followed the Dysons with a fiendish
malignity. When threatening to blow out Mrs. Dyson’s brains, Peace
had the effrontery to ask a bystander to “bear him witness that she
had struck him with a life-preserver.” This idea was a pure myth.
The preserver existed only in the foul imagination of the criminal,
and the struggle with Mr. Dyson on the 29th November, 1876, a still
bolder fiction. It is possible that the crime was unpremeditated, and
that annoyance rather than murder was intended. But a man who
makes a revolver the instrument of annoyance cannot guard against
the most dreaded contingencies.
Mr. Campbell Foster was justly enough precluded from making
any reference to Peace’s attempted escape from the railway train.
But it is not difficult to understand the motives under which the
desperate leap was taken.
If Peace had possessed any confidence in his ability to support
the plea set up in his behalf, there would have been no attempt to
escape. But he was awnre of what awaited him.
He knew enough of Mrs. Dyson to fear that her testimony was not
likely to be shaken. Every incidence in her career, so far as it was
known to counsel, was reproduced for the purpose of disconcerting
and discrediting her. Nevertheless, she left the witness-box with her
evidence unshaken.
Thus has Charles Peace been condemned. Hunted down while not
yet fifty, there is in every feature of his forbidding face evidence that
such a career is as unprofitable as it is criminal.
It is difficult to conceive what this malefactor might have been
under other and brighter auspices. But, dedicated to crime from his
youth upward, as years passed away, conscience, which in his case
was never tender, became “seared as with a hot iron.”
When the final stage in his trial was reached, and Peace was
asked if he had anything to say, he whimpered out, “Is there any
use of saying anything now?”
But in his cell the convict collapses, and his courage proves
melodramatic.
CHAPTER CLVIII.

PRISONERS AND THEIR CUSTODIANS.

One of the most remarkable and daring exploits of our time, and
one which more than any other of his adventures awakened the
public mind to the desperate and reckless nature of the man was his
attempt to escape while in the charge of his warders in the railway
carriage. This might be considered the culminating point of his
lawless life, and had he been without handcuffs, and possessed of
his favourite weapon—​a six-chambered revolver—​we would not have
given much for the lives of his two custodians. It was indeed
fortunate for them that the wild beast under their care was safely
manacled, and, indeed, the great body of the people had no idea of
the risks run by the servants of the law in dealing with ruffians of
Peace’s type. We subjoin an interesting account given by an officer,
and printed in Chambers’s Journal of

A PERILOUS RIDE WITH A CONVICT.


One of my journeys called me away to a town in Suffolk, where I
was ordered to take charge of a prisoner to be discharged the next
day from one of the local gaols, in which he had been undergoing a
year’s imprisonment for a criminal assault.
The man had been let out on a ticket-of-leave from the “Defence”
hulk at Woolwich, and had speedily, as it appeared, got into trouble
down in the country.
As he was merely “wanted” to complete his original sentence—​
having broken his ticket-of-leave—​there could be no bother about
apprehending him inside the prison, and using such precautions for
his safe keeping as seemed best to my judgment.
Just as I was about to leave the office in Bow-street, one of my
comrades with whom I was rather intimate came in, having finished
a journey such as I was myself about to set off on.
“Going out, Tom?” he asked; and on my telling him where I was
bound for, he continued—​“Better have this ‘barker,’ Tom—​you may
find it useful.”
At the same time he produced a small pocket pistol, which he
held out for my acceptance.
“I have not got any powder,” he added; but here are some caps
and bullets.”
It seemed needless to remark that this was before the days of
revolvers and patent cartridges; we had then to load in the old
fashion, and had merely got as far as the introduction of the
percussion cap.
I had never before carried anything more deadly by way of
protection than a life-preserver, but as my friend seemed to mean a
kindness, I made no ado about accepting his offer; and having
“capped” it there and then, I consigned it to the side pocket of a
pilot coat, which I wore buttoned over my uniform.
My journey down to Suffolk calls for no particular notice. In due
time the railway deposited me at my destination, and left me with
plenty of leisure to call upon the governor of the prison over night,
with a view to my carrying off my charge the next morning. I asked
what sort of a customer I would have to deal with, and must confess
that I did not feel much encouraged with the reply,
“He is what I would call a nasty customer,” was the answer. “He
has given us a deal of trouble while we have had charge of him;
continually breaking prison rules, and more than once he has tried to
commit suicide in the most determined manner by tearing open the
veins in his arms with his finger-nails.”
This account of matters was not, as may well be supposed, at all
enlivening; and when the governor added that the man was a
perfect giant, and had been a “navvy” before he fell into evil
courses, I began to fear that my work was cut out for me. However,
there was no help for it.
The inn where I had taken up my quarters stood right opposite
the gaol entrance, and as the street was somewhat of the
narrowest, the most complete view of all comers and goers could be
commanded from the front of my temporary residence.
Next morning found me seated at a very comfortable breakfast,
and the weather being fine, the window of the private parlour was
open, affording a perfect view of all that might take place at the
prison door opposite.
While I was absorbed in the good cheer before me, I was startled
by an exclamation from both the landlady and her daughter, which
caused me to look up and instinctively to glance across the street.
“Did you ever see such a big, coarse, and clumsy-looking
woman?” exclaimed the younger of my entertainers.
“Or is it a woman at all?” added her mother.
My attention was at once riveted upon the newcomer, whom I
somehow could not avoid connecting with the criminal it would so
soon become my duty to apprehend.
Without saying a word to the two ladies, I carefully and closely
watched every movement of the party opposite during the remainder
of my morning meal. More than once I caught myself mentally
repeating my landlady’s query: “Is it a woman, after all?”
The “it” must be excused, as the point was so entirely doubtful.
For a woman, the individual was very considerably above the
average height, and her whole physique indicated far more than the
average strength of womankind.
There was a swagger in her walk, too, most unlike the carriage of
a female. I was fairly puzzled, and none the less so that I had twice
noticed her ringing the prison bell, and that I knew there was but
one individual to be discharged that morning, and that it was close
upon my time to go and look after him.
I had barely finished my last cup of coffee, when one of the
prison warders came across to say that the wife of my prisoner was
waiting outside, and had twice made a demand to see him; but that
the governor did not care to accede to the request without first
consulting me.
After casting the matter over in my own mind for a minute, I told
the warder that I did not mind the woman being admitted, but that
the two ought to be very closely watched during the interview.
The man re-entered the prison, and within a few minutes I
observed that the woman was called in.
Punctual to my time, I crossed over to the prison, and found my
charge waiting for me, his wife being still with him, and no one in
the room but the governor.
Contrary to my expectations, the prisoner held up his wrists and
submitted to be handcuffed with the most lamb-like docility.
When we got out into the street, I suggested, as there was time
to spare, that the stalwart pair should have a bit of breakfast at my
expense before starting on the journey for town.
I thought the woman seemed a little taken aback at my invitation;
however, it was acceded to; and we entered the inn parlour, where I
requested the landlady to produce a plentiful supply of ham and
eggs; and as the pair preferred ale to tea or coffee, I ordered them
a pint apiece.
I had of course to unlock one hand in the order to allow my
prisoner the free use of his knife and fork; and, after what I had
heard the night before, I thought it was rather risky thing for me to
do, as though he might not attempt to do me any mischief, it was
just possible he might try to inflict some serious mischief on himself.
All, however, passed off safely, and when breakfast was finished, I
told him he must bid his wife good-bye, as I did not want to attract
any attention at the railway station. A kiss was accordingly
exchanged, the bracelets were again attached to the wrists, and we
set off at a brisk pace.
When we got to the station, I learned that the next “up” train was
an express, and that I would have to look sharp, as it might be
expected immediately, and made but a brief stoppage.
The train, in fact, came in almost to a minute after the
information was communicated to me; and I hurried across the
platform, got my man into a second-class carriage—​the
compartment I had only just time to notice was empty.
The whistle sounded, and the train was beginning to move, when
the door was flung violently open, and in jumped the prisoner’s wife,
taking her seat right opposite me.
There was but time for the porter to slam the door, when we
were off. It need not be said that I was very far from being satisfied
with the look of things, and that I had made up my mind to be
carefully on my guard.
I said nothing, being fully determined not to show any
uneasiness, though it must be owned I felt much. Before we had
gone any great way my prisoner turned sideways to me and said:
“Master, my missus and me have some small matters of our own we
would like to talk over; and as they don’t concern you in the least,
p’raps you wouldn’t mind looking out of winder for a minute or two
while we have our talk.”
“That I could not possibly do,” was my immediate answer. My
duty is to keep you always under my eye and control; and besides,
as you have just said, your domestic arrangements can be a matter
of no concern to me, so you can discuss them as freely as you
please without minding my presence.”
This answer seemed to disconcert both of them; but as if by way
of compromise, I at the same moment leant towards the window of
the carriage for a moment, and glanced outside.
My hearing is sharp enough now, but at the time I speak as was
even more acute. Just as I turned my head, I heard, or thought I
heard the man whisper the words: “Both together.” Instantly the
suspicion flashed across my mind that these words related to myself,
and I turned round and faced the couple in a moment.
What I saw in the expression of each of them seemed to warrant
my acting with immediate decision. I seized the man between his
manacled wrists so that he could not raise his hands.
With an instinctive thought I plunged my right hand into the
pocket of my pilot coat, pulled out the pistol my mate had handed to
me, cocked it with my thumb, and holding it within a few inches of
the face of the woman opposite, I looked steadily into her eyes, and
said with emphasis, “If you attempt to stir before we reach the next
station you will certainly be a dead woman!”
It was something fearful to notice the immediate change on that
woman’s countenance. She became of a pallid whiteness, and her
lips had the purple-bluish tinge that indicate so unmistakably an
access of deadly fear. In the highly-dramatic positions I have just
described we sped on until the next stopping station was reached,
and that occupied fully more than twenty minutes.
The moment the train came to a stop I thus addressed the
woman, keeping her “covered” with the muzzle of my pistol: “Leave
the carriage; and, if you value your liberty, make what speed you
can to get into hiding.”
She disappeared instanter; and I felt a heavy load of anxiety lifted
off my mind as she left us, for of all the encounters I most hate, an
encounter with a woman is to be classed foremost.
Not a word passed between my prisoner aad me during the
remainder of the journey to London, which we were no great while
in reaching, and where I duly delivered him into safe keeping at
Bow-street police-office.
Next morning I had to conduct my prisoner to Woolwich, there to
deliver him to the authorities of the hulks, from whom he had
obtained his ticket-of-leave. He seemed to have recovered from his
scare of the day before, and on our journey spoke freely enough,
and with an earnestness that left no doubt of the truth of his
communication.
“Master,” said he, “I am main glad you kept your head yesterday,
and did not lean out of the winder. Had you done so, missus and I
meant to have pitched you out, and taken our chance afterwards of
getting off.
“I was not very likely to be so easily put off my guard,” was the
laconic answer.
“Aye, but master, your danger was not over then for missus and I
had made it up that she was to pin your arms—​and she could a
done it easy—​while I was to smash your head with the ‘darbies.’ We
should then a took a key, got off the bracelets, and heaved you out
of a winder, afore you could come to yourself. That pistol fairly put
us out, for it cowed missus, and she isn’t easily cowed, I tell ye.”
“But the pistol was not loaded,” said I—​“nothing but a cap and an
empty barrel.”
“All the same, master, I’m main glad we failed. Now I’ve thought
it over, I know I could not have escaped. It was known I left in your
charge, and that missus joined us. When your body was found, we’d
a been spotted at once, and most likely both on us would a swung
for it. I’m main glad, I tell you, that you got out o’ the mess, and I
don’t bear you no ill-will for having done your dooty as a man and a
hofficer.”
Never before, to my knowledge, had I been in such deadly peril,
and truly thankful did I inwardly feel for the providential escape I
learned I had just made. I was glad to hand my murderous-minded
charge over to the care of the officers of the “Defence;” and I am
thankful to add that I never heard more of him, or wished to do so.
Among the many persons who had been present at the
examination of Charles Peace was an old acquaintance—​Shearman,
the American detective, of loquacious and anecdotal proclivities.
After the prisoner’s committal he adjourned to an adjoining house
where good entertainment was provided for man and beast. In the
company of the English detectives engaged in the case, police-
sergeants, and inspectors, Mr. Shearman was quite at home. A long,
rambling discussion took place, the leading subject being the merits,
or rather demerits, of our hero. Incidents in detective life became
the order of the day, and, as far as this was concerned, Mr.
Shearman, as usual, “went ahead.” He told a capital story, which, as
this is the last time we shall have to take notice of him, we give in
his own words:—​

TRACKING A FUGITIVE OVER THE OCEAN.


I am not Pollaky or Paddington Green, neither am I Inspector
Webb, nor Detective Bull of the City force, said Mr. Shearman. My
status in society is that of a banker’s clerk. I hold an appointment in
a Midland Counties firm, which I entered upon five-and-twenty years
ago.
I had reached what is termed the “ripe middle age,” when some
months since the even current of my life was interrupted by the
following event:—
The establishment with which I have been so long associated is
well known, and has gained a reputation by the quiet, respectable
character of its business transactions.
It does not indulge in speculative ventures, and hence has
escaped many of the misfortunes and missed no little of the
agitation which some banking firms have had to encounter.
Occasionally we have been startled by the presentation of a bad
note, a forged cheque, and other cunningly-devised schemes of well-
practiced swindlers to impose on our simplicity and credulity, which
circumstances have forced us into the excitement of judicial
investigations.
Thus, from time to time, I was brought into contact with some of
the most celebrated detectives of the day. I still remember the
feelings of admiration with which I witnessed the skill and sagacity
of such men as John Forrister, Leadbeater, the Bow-street officer,
Inspector Wicher, and other police officers, in tracking and detecting
a swindler.
At that period I little dreamt that my quiet life would be disturbed
by an eventful episode, such as I am about to relate.
On the morning of the 28th of September, 186-, I was at my post
as usual, when a message from the bank manager summoned me to
his presence. I saw at a glance, on entering the room, that
something had happened.
My chief informed me that a customer of the bank, whom, for
obvious reasons, I will call Mr. Hooker, had absconded.
I was aware, not only that he was under an engagement to
liquidate a considerable claim we had against him, but that he had
recently fixed a day for the fulfilment of his promise, assuring us that
he should be in the immediate receipt of a large sum of money,
which would enable him to pay his debt, and leave a balance to his
credit in our hands.
The statement of his expected funds was no fiction—​he duly
received them—​but instead of appropriating his newly-acquired
wealth to the honest discharge of our claim, he clandestinely left his
home, and before the intelligence of his departure had reached us,
he was half-way to Canada.
The manager’s indignation at the fradulent conduct of an
individual whom he had believed to be an honourable man, and had
trusted as such, did not surprise me. Neither was I astonished when
he told me he would do all in his power to punish the absconding
debtor, if means could be adopted to discover and arrest him in his
flight.
It was a matter for serious deliberation. Ultimately, acting on an
impulse I could not control, I proffered my services to go in pursuit
of the defaulter. They were accepted.
The same evening, in company with one of our directors, I left by
the mail train for Liverpool, reaching that place some little time after
midnight. The object of this journey was to endeavour to ascertain,
through the Liverpool detectives, when and by what ship Mr. Hooker
had sailed, as well as his destination, in order that we might arrive
at a conclusion as to the propriety of my crossing the Atlantic in
pursuit.
Early the following morning we were at the headquarters of the
detective police. We related the nature of our mission, and the
services of one of their most efficient officers were placed at our
disposal.
He was evidently well known at all the shipping offices. In less
than an hour he furnished us with every information we could obtain
in Liverpool. He ascertained that Hooker had sailed for Quebec
seven days previously in the Canada mail packet ship “Belgian,” and
had booked through to Montreal; and he added the still more
important facts that the delinquent had with him his wife, sister-in-
law, and two children, and further, that he was in possession of a roll
of bank notes at the time he secured the berths.
Had he gone alone I doubt whether I should have had the
courage to proceed farther; but the fact of his being encumbered
with the ladies, the children, and a large quantity of baggage was a
set-off against his seven days’ start, and considerably altered my
views.
With such a drag on his movements, I felt there was a hope of
success, and at once accepted the responsibility of following him.
A berth was secured on board the “China,” of the Cunard line, and
on Saturday, the 30th of September, 4.30 p.m., I found myself
afloat, and the docks of Liverpool becoming fainter and fainter.
Fortunately the weather was extremely fine; and as we steamed
down the Mersey the scene and the event was one of unusual
interest to me.
The interior of a first-class mail packet just starting on her
voyage, and its animated appearance, have often been described. I
need only say there were over two hundred passengers on board,
No. and that my immediate companions were a French gentleman,
90. a Spaniard and his wife, a Scotch physician (who was in a
state of complete prostration three-fourths of the voyage), a ship-
builder from St. John’s, N.B., and his two daughters, the chaplain of
the ship and his wife, and Mr. Tucker, an intelligent man from
Philadelphia, who, during the voyage, gave me such valuable
information, and introduced me to some Canadian merchants on
board. These gentlemen subsequently rendered me great assistance
in the prosecution of the object I had in view.
A ROPE IS FLUNG OVER LAURA’S HEAD, AND HER ARMS
ARE CLOSELY PINIONED.

One of the most agreeable interludes of our voyage occurred


during our detention at Queenstown for the mail bags.
A delay of the mail train enabled us to pay a visit to the lovely
Cove of Cork. We landed at the pleasant quay, ascended Lookout
Hill, and partook of the hospitality of the Queen’s Hotel.

You might also like