100% found this document useful (10 votes)
91 views

Complete Download Python Data Visualization Cookbook Milovanović PDF All Chapters

Cookbook

Uploaded by

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

Complete Download Python Data Visualization Cookbook Milovanović PDF All Chapters

Cookbook

Uploaded by

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

Get ebook downloads in full at ebookname.

com

Python Data Visualization Cookbook Milovanovi

https://ebookname.com/product/python-data-visualization-
cookbook-milovanovic/

OR CLICK BUTTON

DOWNLOAD EBOOK

Explore and download more ebook at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Data Visualization with Python and JavaScript Scrape


Clean Explore Transform Your Data 1st Edition Kyran
Dale

https://ebookname.com/product/data-visualization-with-python-and-
javascript-scrape-clean-explore-transform-your-data-1st-edition-
kyran-dale/

Python Cookbook 2nd ed Edition Beazley

https://ebookname.com/product/python-cookbook-2nd-ed-edition-
beazley/

Python Machine Learning Cookbook 1st Edition Joshi

https://ebookname.com/product/python-machine-learning-
cookbook-1st-edition-joshi/

MisReading Plato 1st Edition Matthew Clemente

https://ebookname.com/product/misreading-plato-1st-edition-
matthew-clemente/
Research Design in Counseling 3rd Edition P. Paul
Heppner

https://ebookname.com/product/research-design-in-counseling-3rd-
edition-p-paul-heppner/

Artificial Intelligence Approaches Tools and


Applications Approaches Tools and Applications 1st
Edition Brent M. Gordon

https://ebookname.com/product/artificial-intelligence-approaches-
tools-and-applications-approaches-tools-and-applications-1st-
edition-brent-m-gordon/

The Christian Hope Brian Hebblethwaite

https://ebookname.com/product/the-christian-hope-brian-
hebblethwaite/

Plant user specification guide 1st Edition James


Hitchmough

https://ebookname.com/product/plant-user-specification-guide-1st-
edition-james-hitchmough/

Special Edition Using WordPerfect 12 Laura Acklen

https://ebookname.com/product/special-edition-using-
wordperfect-12-laura-acklen/
Weapons Warfare Ancient Medieval John Powell

https://ebookname.com/product/weapons-warfare-ancient-medieval-
john-powell/
www.it-ebooks.info
Python Data
Visualization Cookbook

Over 60 recipes that will enable you to learn how to


create attractive visualizations using Python's most
popular libraries

Igor Milovanović

BIRMINGHAM - MUMBAI

www.it-ebooks.info
Python Data Visualization Cookbook

Copyright © 2013 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the publisher,
except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies
and products mentioned in this book by the appropriate use of capitals. However, Packt
Publishing cannot guarantee the accuracy of this information.

First published: November 2013

Production Reference: 1191113

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78216-336-7

www.packtpub.com

Cover Image by Gorkee Bhardwaj ([email protected])

www.it-ebooks.info
Credits

Author Project Coordinator


Igor Milovanović Rahul Dixit

Reviewers Proofreaders
Tarek Amr Amy Johnson
Simeone Franklin Lindsey Thomas
Jayesh K. Gupta
Indexer
Kostiantyn Kucher
Mariammal Chettiyar
Kenneth Emeka Odoh
Graphics
Acquisition Editor Abhinash Sahu
James Jones
Production Coordinator
Lead Technical Editor Shantanu Zagade
Ankita Shashi
Cover Work
Technical Editors Shantanu Zagade
Pratik More
Amit Ramadas
Ritika Singh

Copy Editors
Brandt D'Mello
Janbal Dharmaraj
Deepa Nambiar
Kirti Pai
Laxmi Subramanian

www.it-ebooks.info
About the Author

Igor Milovanović is an experienced developer with a strong background in Linux


system and software engineering. He has skills in building scalable data-driven
distributed software-rich systems.

He is an Evangelist for high-quality systems design who holds strong interests in software
architecture and development methodologies. He is always persistent on advocating
methodologies that promote high-quality software, such as test-driven development,
one-step builds, and continuous integration.

He also possesses solid knowledge of product development. Having field experience and
official training, he is capable of transferring knowledge and communication flow from
business to developers and vice versa.

I am most grateful to my fiance for letting me spend endless hours on the


work instead with her and for being an avid listener to my endless book
monologues. I want to also thank my brother for always being my strongest
supporter. I am thankful to my parents for letting me develop myself in
various ways and become the person I am today.
I could not write this book without enormous energy from open source
community that developed Python, matplotlib, and all libraries that we
have used in this book. I owe the most to the people behind all these
projects. Thank you.

www.it-ebooks.info
About the Reviewers

Tarek Amr achieved his postgraduate degree in Data Mining and Information Retrieval from
the University of East Anglia. He has about 10 years' experience in Software Development.
He has been volunteering in Global Voices Online (GVO) since 2007, and currently he is the
local ambassador of the Open Knowledge Foundation (OKFN) in Egypt. Words such as Open
Data, Government 2.0, Data Visualisation, Data Journalism, Machine Learning, and Natural
Language Processing are like music to his ears.

Tarek's Twitter handle is @gr33ndata and his homepage is


http://tarekamr.appspot.com/.

Jayesh K. Gupta is the Lead Developer of Matlab Toolbox for Biclustering Analysis (MTBA).
He is currently an undergraduate student and researcher at IIT Kanpur. His interests lie in the
field of pattern recognition. His interests also lie in basic sciences, recognizing them as the
means of analyzing patterns in nature. Coming to IIT, he realized how this analysis is being
augmented by Machine Learning algorithms with various diverse applications. He believes
that augmenting human thought with machine intelligence is one of the best ways to advance
human knowledge. He is a long time technophile and a free-software Evangelist. He usually
goes by the handle, rejuvyesh online. He is also an avid reader and his books can be checked
out at Goodreads. Checkout his projects at Bitbucket and GitHub. For all links visit http://
home.iitk.ac.in/~jayeshkg/. He can be contacted at [email protected].

www.it-ebooks.info
Kostiantyn Kucher was born in Odessa, Ukraine. He received his Master's degree in
Computer Science from Odessa National Polytechnic University in 2012. He used Python
as well as Matplotlib and PIL for Machine Learning and Image Recognition purposes.

Currently, Kostiantyn is a PhD student in Computer Science specializing in Information


Visualization. He conducts his research under the supervision of Prof. Dr. Andreas Kerren
with the ISOVIS group at the Computer Science Department of Linnaeus University
(Växjö, Sweden).

Kenneth Emeka Odoh performs research on state of the art Data Visualization
techniques. His research interest includes exploratory search where the users are
guided to their search results using visual clues.

Kenneth is proficient in Python programming. He has presented a Python conference


talk at Pycon, Finland in 2012 where he spoke about Data Visualization in Django to
a packed audience.

He currently works as a Graduate Researcher at the University of Regina, Canada.


He is a polyglot with experience in developing applications in C, C++, Python, and
Java programming languages.

When Kenneth is not writing source codes, you can find him singing at the Campion College
chant choir.

www.it-ebooks.info
www.PacktPub.com

Support files, eBooks, discount offers and more


You might want to visit www.PacktPub.com for support files and downloads related to
your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up
for a range of free newsletters and receive exclusive discounts and offers on Packt books
and eBooks.

TM

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's entire library of books.

Why Subscribe?
ff Fully searchable across every book published by Packt

ff Copy and paste, print and bookmark content


ff On demand and accessible via web browser

Free Access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials for
immediate access.

www.it-ebooks.info
www.it-ebooks.info
Table of Contents
Preface 1
Chapter 1: Preparing Your Working Environment 5
Introduction 5
Installing matplotlib, NumPy, and SciPy 6
Installing virtualenv and virtualenvwrapper 8
Installing matplotlib on Mac OS X 10
Installing matplotlib on Windows 11
Installing Python Imaging Library (PIL) for image processing 12
Installing a requests module 14
Customizing matplotlib's parameters in code 14
Customizing matplotlib's parameters per project 16
Chapter 2: Knowing Your Data 19
Introduction 19
Importing data from CSV 20
Importing data from Microsoft Excel files 22
Importing data from fixed-width datafiles 25
Importing data from tab-delimited files 27
Importing data from a JSON resource 28
Exporting data to JSON, CSV, and Excel 31
Importing data from a database 36
Cleaning up data from outliers 40
Reading files in chunks 46
Reading streaming data sources 48
Importing image data into NumPy arrays 50
Generating controlled random datasets 56
Smoothing the noise in real-world data 64

www.it-ebooks.info
Table of Contents
Chapter 3: Drawing Your First Plots and Customizing Them 71
Introduction 72
Defining plot types – bar, line, and stacked charts 72
Drawing a simple sine and cosine plot 78
Defining axis lengths and limits 81
Defining plot line styles, properties, and format strings 84
Setting ticks, labels, and grids 89
Adding a legend and annotations 92
Moving spines to the center 95
Making histograms 96
Making bar charts with error bars 99
Making pie charts count 101
Plotting with filled areas 103
Drawing scatter plots with colored markers 105
Chapter 4: More Plots and Customizations 109
Introduction 109
Setting the transparency and size of axis labels 110
Adding a shadow to the chart line 113
Adding a data table to the figure 116
Using subplots 118
Customizing grids 121
Creating contour plots 125
Filling an under-plot area 128
Drawing polar plots 131
Visualizing the filesystem tree using a polar bar 134
Chapter 5: Making 3D Visualizations 139
Introduction 139
Creating 3D bars 139
Creating 3D histograms 143
Animating in matplotlib 146
Animating with OpenGL 150

ii

www.it-ebooks.info
Table of Contents

Chapter 6: Plotting Charts with Images and Maps 157


Introduction 157
Processing images with PIL 158
Plotting with images 164
Displaying an image with other plots in the figure 168
Plotting data on a map using Basemap 172
Plotting data on a map using Google Map API 177
Generating CAPTCHA images 183
Chapter 7: Using Right Plots to Understand Data 189
Introduction 189
Understanding logarithmic plots 190
Understanding spectrograms 193
Creating a stem plot 198
Drawing streamlines of vector flow 201
Using colormaps 205
Using scatter plots and histograms 210
Plotting the cross-correlation between two variables 217
Importance of autocorrelation 220
Chapter 8: More on matplotlib Gems 225
Introduction 225
Drawing barbs 225
Making a box and a whisker plot 229
Making Gantt charts 232
Making errorbars 237
Making use of text and font properties 240
Rendering text with LaTeX 246
Understanding the difference between pyplot and OO API 250
Index 257

iii

www.it-ebooks.info
Table of Contents

iv

www.it-ebooks.info
Preface
The best data is the data that we can see and understand. As developers, we want to
create and build the most comprehensive and understandable visualizations. It is not always
simple; we need to find the data, read it, clean it, massage it, and then use the right tool to
visualize it. This book explains the process of how to read, clean, and visualize the data into
information with straight and simple (and not so simple) recipes.

How to read local data, remote data, CSV, JSON, and data from relational databases are all
explained in this book.

Some simple plots can be plotted with a simple one-liner in Python using matplotlib, but
doing more advanced charting requires knowledge of more than just Python. We need to
understand the information theory and human perception aesthetics to produce the most
appealing visualizations.

This book will explain some practices behind plotting with matplotlib in Python, statistics used,
and usage examples for different charting features we should use in an optimal way.

This book is written and the code is developed on Ubuntu 12.03 using Python 2.7,
IPython 0.13.2, virtualenv 1.9.1, matplotlib 1.2.1, NumPy 1.7.1, and SciPy 0.11.0.

What this book covers


Chapter 1, Preparing Your Working Environment, covers a set of installation recipes and
advices on how to install the required Python packages and libraries on your platform.

Chapter 2, Knowing Your Data, introduces you to common data formats and how to read and
write them, be it CSV, JSON, XSL, or relational databases.

Chapter 3, Drawing Your First Plots and Customizing Them, starts with drawing simple plots
and covers some of the customization.

Chapter 4, More Plots and Customizations, follows up from previous chapter and covers more
advanced charts and grid customization.

www.it-ebooks.info
Preface

Chapter 5, Making 3D Visualizations, covers three-dimensional data visualizations such as


3D bars, 3D histograms, and also matplotlib animations.

Chapter 6, Plotting Charts with Images and Maps, covers image processing, projecting data
onto maps, and creating CAPTCHA test images.

Chapter 7, Using Right Plots to Understand Data, covers explanations and recipes on some
more advanced plotting techniques such as spectrograms and correlations.

Chapter 8, More on matplotlib Gems, covers a set of charts such as Gantt charts, box plots,
and whisker plots, and also explains how to use LaTeX for rendering text in matplotlib.

What you need for this book


For this book, you will need Python 2.7.3 or a later version installed on your operating system.
This book was written using Ubuntu 12.03's Python default version (2.7.3).

Other software packages used in this book are IPython, which is an interactive Python
environment that is very powerful, and flexible. This can be installed using package
managers for Linux-based OSes or prepared installers for Windows and Mac OSes.

If you are new to Python installation and software installation in general, it is very much
recommended to use prepackaged scientific Python distributions such as Anaconda,
Enthought Python Distribution, or Python(X,Y).

Other required software mainly comprises of Python packages that are all installed using
the Python installation manager, pip, which itself is installed using Python's easy_install
setup tool.

Who this book is for


Python Data Visualization Cookbook is for developers who already know about Python
programming in general. If you have heard about data visualization but don't know where to
start, this book will guide you from the start and help you understand data, data formats,
data visualization, and how to use Python to visualize data.

You will need to know some general programming concepts, and any kind of programming
experience will be helpful. However, the code in this book is explained almost line by line. You
don't need math for this book; every concept that is introduced is thoroughly explained in plain
English, and references are available for further interest in the topic.

Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of
information. Here are some examples of these styles, and an explanation of their meaning.

www.it-ebooks.info
Preface

Code words in text are shown as follows: "We packed our little demo in class DemoPIL,
so that we can extend it easily, while sharing the common code around the demo function,
run_fixed_filters_demo."

A block of code is set as follows:


def _load_image(self, imfile):
self.im = mplimage.imread(imfile)

When we wish to draw your attention to a particular part of a code block, the relevant lines or
items are set in bold:
# tidy up tick labels size
all_axes = plt.gcf().axes
for ax in all_axes:
for ticklabel in ax.get_xticklabels() + ax.get_yticklabels():
ticklabel.set_fontsize(10)

Any command-line input or output is written as follows:


$ sudo python setup.py install

New terms and important words are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: "We then set up a label for
the stem plot and the position of baseline, which defaults to 0."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or may have disliked. Reader feedback is important for us to
develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to [email protected],


and mention the book title via the subject of your message.

www.it-ebooks.info
Preface

If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to
get the most from your purchase.

Downloading the example code


You can download the example code files for all Packt books you have purchased from your
account at http://www.packtpub.com. If you purchased this book elsewhere, you can
visit http://www.packtpub.com/support and register to have the files e-mailed
directly to you.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen.
If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be
grateful if you would report this to us. By doing so, you can save other readers from frustration
and help us improve subsequent versions of this book. If you find any errata, please report them
by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on
the errata submission form link, and entering the details of your errata. Once your errata are
verified, your submission will be accepted and the errata will be uploaded on our website, or
added to any list of existing errata, under the Errata section of that title. Any existing errata can
be viewed by selecting your title from http://www.packtpub.com/support.

Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,
we take the protection of our copyright and licenses very seriously. If you come across any
illegal copies of our works, in any form, on the Internet, please provide us with the location
address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions
You can contact us at [email protected] if you are having a problem with any
aspect of the book, and we will do our best to address it.

www.it-ebooks.info
Preparing Your Working
1
Environment
In this chapter, we will cover the following recipes:

ff Installing matplotlib, NumPy, and SciPy


ff Installing virtualenv and virtualenvwrapper
ff Installing matplotlib on Mac OS X
ff Installing matplotlib on Windows
ff Installing Python Imaging Library (PIL) for image processing
ff Installing a requests module
ff Customizing matplotlib's parameters in code
ff Customizing matplotlib's parameters per project

Introduction
This chapter introduces the reader to the essential tooling and installation and configuration
of them. This is a necessary work and common base for the rest of the book. If you have never
used Python for data and image processing and visualization, it is advised not to skip this
chapter. Even if you do skip it, you can always return to this chapter in case you need to
install some supporting tool or verify what version you need to support the current solution.

www.it-ebooks.info
Preparing Your Working Environment

Installing matplotlib, NumPy, and SciPy


This chapter describes several ways of installing matplotlib and required dependencies
under Linux.

Getting ready
We assume that you already have Linux (preferably Debian/Ubuntu or RedHat/SciLinux)
installed and Python installed on it. Usually, Python is already installed on the mentioned
Linux distributions and, if not, it is easily installable through standard means. We assume
that Python 2.7+ Version is installed on your workstation.

Almost all code should work with Python 3.3+ Versions, but because most
operating systems still deliver Python 2.7 (some even Python 2.6) we decided
to write the Python 2.7 Version code. The differences are small, mainly in
version of packages and some code (xrange should be substituted with range
in Python 3.3+).

We also assume that you know how to use your OS package manager in order to install
software packages and know how to use a terminal.

Build requirements must be satisfied before matplotlib can be built.

matplotlib requires NumPy, libpng, and freetype as build dependencies. In order to be able to
build matplotlib from source, we must have installed NumPy. Here's how to do it:

Install NumPy (at least 1.4+, or 1.5+ if you want to use it with Python 3) from
http://www.numpy.org/.

NumPy will provide us with data structures and mathematical functions for
using it with large datasets. Python's default data structures such as tuples,
lists, or dictionaries are great for insertions, deletions, and concatenation.
NumPy's data structures support "vectorized" operations and are very efficient
for use and for executions. They are implemented with Big Data in mind and
rely on C implementations that allow efficient execution time.
SciPy, building on top of NumPy, is the de facto standard's scientific and
numeric toolkit for Python comprising great selection of special functions and
algorithms, most of them actually implemented in C and Fortran, coming from
the well-known Netlib repository (see http://www.netlib.org).

www.it-ebooks.info
Chapter 1

Perform the following steps for installing NumPy:

1. Install Python-NumPy package:


$ sudo apt-get install python-numpy

2. Check the installed version:


$ python -c 'import numpy; print numpy.__version__'

3. Install the required libraries:

‰‰ libpng 1.2: PNG files support (requires zlib)


‰‰ freetype 1.4+: True type font support
$ sudo apt-get install build-dep python-matplotlib

If you are using RedHat or variation of this distribution (Fedora, SciLinux, or CentOS)
you can use yum to perform same installation:
$ su -c 'yum-builddep python-matplotlib'

How to do it...
There are many ways one can install matplotlib and its dependencies: from source, from
precompiled binaries, from OS package manager, and with prepackaged python distributions
with built-in matplotlib.

Most probably the easiest way is to use your distribution's package manager. For Ubuntu that
should be:
# in your terminal, type:
$ sudo apt-get install python-numpy python-matplotlib python-scipy

If you want to be on the bleeding edge, the best option is to install from source. This path
comprises a few steps: Get the source, build requirements, and configure, compile,
and install.

Download the latest source from code host www.github.com by following these steps:
$ cd ~/Downloads/
$ wget https://github.com/downloads/matplotlib/matplotlib/matplotlib-
1.2.0.tar.gz
$ tar xzf matplotlib-1.2.0.tar.gz
$ cd matplotlib-1.2.0
$ python setup.py build
$ sudo python setup.py install

www.it-ebooks.info
Preparing Your Working Environment

Downloading the example code


You can download the example code files for all Packt books you have
purchased from your account at http://www.packtpub.com. If you
purchased this book elsewhere, you can visit http://www.packtpub.
com/support and register to have the files e-mailed directly to you.

How it works...
We use standard Python Distribution Utilities, known as Distutils, to install matplotlib from
source code. This procedure requires us to previously install dependencies, as we already
explained in the Getting ready section of this recipe. The dependencies are installed using
the standard Linux packaging tools.

There's more...
There are more optional packages that you might want to install depending on what your data
visualization projects are about.

No matter what project you are working on, we recommend installing IPython—an Interactive
Python shell that supports PyLab mode where you already have matplotlib and related
packages, such as NumPy and SciPy, imported and ready to play with! Please refer to
IPython's official site on how to install it and use it—it is, though, very straightforward.

Installing virtualenv and virtualenvwrapper


If you are working on many projects simultaneously, or even just switching between them
frequently, you'll find that having everything installed system-wide is not the best option and
can bring problems in future on different systems (production) where you want to run your
software. This is not a good time to find out that you are missing a certain package or have
versioning conflicts between packages that are already installed on production system;
hence, virtualenv.

virtualenv is an open source project started by Ian Bicking that enables a developer to isolate
working environments per project, for easier maintenance of different package versions.

For example, you inherited legacy Django website based on Django 1.1 and Python 2.3, but at
the same time you are working on a new project that must be written in Python 2.6. This is my
usual case—having more than one required Python version (and related packages) depending
on the project I am working on.

www.it-ebooks.info
Chapter 1

virtualenv enables me to easily switch to different environments and have the same package
easily reproduced if I need to switch to another machine or to deploy software to a production
server (or to a client's workstation).

Getting ready
To install virtualenv, you must have workable installation of Python and pip. Pip is a tool for
installing and managing Python packages, and it is a replacement for easy install. We will
use pip through most of this book for package management. Pip is easily installed, as root
executes the following line in your terminal:
# easy_install pip

virtualenv by itself is really useful, but with the help of virtualenvwrapper, all this becomes
easy to do and also easy to organize many virtual environments. See all the features at
http://virtualenvwrapper.readthedocs.org/en/latest/#features.

How to do it...
By performing the following steps you can install the virtualenv and virtualenvwrapper tools:

1. Install virtualenv and virtualenvwrapper:


$ sudo pip virtualenv
$ sudo pip virtualenvwrapper
# Create folder to hold all our virtual environments and export
the path to it.
$ export VIRTENV=~/.virtualenvs
$ mkdir -p $VIRTENV
# We source (ie. execute) shell script to activate the wrappers
$ source /usr/local/bin/virtualenvwrapper.sh
# And create our first virtual environment
$ mkvirtualenv virt1

2. You can now install our favorite package inside virt1:


(virt1)user1:~$ pip install matplotlib

3. You will probably want to add the following line to your ~/.bashrc file:
source /usr/loca/bin/virtualenvwrapper.sh

Few useful and most frequently used commands are as follows:

ff mkvirtualenv ENV: This creates virtual environment with name ENV and
activates it
ff workon ENV: This activates the previously created ENV
ff deactivate: This gets us out of the current virtual environment

www.it-ebooks.info
Preparing Your Working Environment

Installing matplotlib on Mac OS X


The easiest way to get matplotlib on Mac OS X is to use prepackaged python distributions
such as Enthought Python Distribution (EPD). Just go to the EPD site and download and
install the latest stable version for your OS.

In case you are not satisfied with EPD or cannot use it for other reasons such as versions
distributed with it, there is a manual (read: harder) way of installing Python, matplotlib,
and its dependencies.

Getting ready
We will use the Homebrew project that eases installation of all software that Apple did not
install on your OS, including Python and matplotlib. Under the hood, Homebrew is a set of
Ruby and Git that automate download and installation. Following these instructions should
get the installation working. First, we will install Homebrew, and then Python, followed by
tools such as virtualenv, then dependencies for matplotlib (NumPy and SciPy), and finally
matplotlib. Hold on, here we go.

How to do it...
1. In your Terminal paste and execute the following command:
ruby <(curl -fsSkL raw.github.com/mxcl/homebrew/go)

After the command finishes, try running brew update or brew doctor to verify that
installation is working properly.

2. Next, add the Homebrew directory to your system path, so the packages you install
using Homebrew have greater priority than other versions. Open ~/.bash_profile
(or /Users/[your-user-name]/.bash_profile) and add the following line to
the end of file:
export PATH=/usr/local/bin:$PATH

3. You will need to restart the terminal so it picks a new path. Installing Python is as
easy as firing up another one-liner:
brew install python --framework --universal

This will also install any prerequisites required by Python.

4. Now, you need to update your path (add to the same line):
export PATH=/usr/local/share/python:/usr/local/bin:$PATH

5. To verify that installation worked, type python --version at the command line,
you should see 2.7.3 as the version number in the response.

10

www.it-ebooks.info
Chapter 1

6. You should have pip installed by now. In case it is not installed, use easy_install
to add pip:
$ easy_install pip

7. Now, it's easy to install any required package; for example, virtualenv and
virtualenvwrapper are useful:
pip install virtualenv
pip install virtualenvwrapper

8. Next step is what we really wanted to do all along—install matplotlib:


pip install numpy
brew install gfortran
pip install scipy

Mountain Lion users will need to install the development version


of SciPy (0.11) by executing the following line:
pip install -e git+https://github.com/scipy/
scipy#egg=scipy-dev

9. Verify that everything is working. Call Python and execute the following commands:
import numpy
print numpy.__version__
import scipy
print scipy.__version__
quit()

10. Install matplotlib:


pip install matplotlib

Installing matplotlib on Windows


In this recipe, we will demonstrate how to install Python and start working with matplotlib
installation. We assume Python was not previously installed.

Getting ready
There are two ways of installing matplotlib on Windows. The easier way is by installing
prepackaged Python environments such as EPD, Anaconda and Python(x,y). This is the
suggested way to install Python, especially for beginners.

11

www.it-ebooks.info
Preparing Your Working Environment

The second way is to install everything using binaries of precompiled matplotlib and required
dependencies. This is more difficult as you have to be careful about the versions of NumPy
and SciPy you are installing, as not every version is compatible with the latest version of
matplotlib binaries. The advantage in this is that you can even compile your particular
versions of matplotlib or any library as to have the latest features, even if they are not
provided by authors.

How to do it...
The suggested way of installing free or commercial Python scientific distributions is as easy as
following the steps provided on the project's website.

If you just want to start using matplotlib and don't want to be bothered with Python versions
and dependencies, you may want to consider using the Enthought Python Distribution (EPD).
EPD contains prepackaged libraries required to work with matplotlib and all the required
dependencies (SciPy, NumPy, IPython, and more).

As usual, we download Windows Installer (*.exe) that will install all the code we need to start
using matplotlib and all recipes from this book.

There is also a free scientific project Python(x,y) (http://code.google.com/p/


pythonxy/) for Windows 32-bit system that contains all dependencies resolved, and is an
easy (and free!) way of installing matplotlib on Windows. Because Python(x,y) is compatible
with Python modules installers, it can be easily extended with other Python libraries. No
Python installation should be present on the system before installing Python(x,y).

Let me shortly explain how we would install matplotlib using precompiled Python, NumPy,
SciPy, and matplotlib binaries. First, we download and install standard Python using official
MSI Installer for our platform (x86 or x86-64). After that, download official binaries for NumPy
and SciPy and install them first. When you are sure that NumPy and SciPy are properly
installed, then we download the latest stable release binary for matplotlib and install it by
following the official instructions.

There's more...
Note that many examples are not included in the Windows installer. If you want to try the
demos, download the matplotlib source and look in the examples subdirectory.

Installing Python Imaging Library (PIL) for


image processing
Python Imaging Library (PIL) enables image processing using Python, has an extensive file
format support, and is powerful enough for image processing.

12

www.it-ebooks.info
Chapter 1

Some popular features of PIL are fast access to data, point operations, filtering, image
resizing, rotation, and arbitrary affine transforms. For example, the histogram method
allows us to get statistics about the images.

PIL can also be used for other purposes, such as batch processing, image archiving, creating
thumbnails, conversion between image formats, and printing images.

PIL reads a large number of formats, while write support is (intentionally) restricted to the
most commonly used interchange and presentation formats.

How to do it...
The easiest and most recommended way is to use your platform's package managers.
For Debian/Ubuntu use the following commands:
$ sudo apt-get build-dep python-imaging
$ sudo pip install http://effbot.org/downloads/Imaging-1.1.7.tar.gz

How it works...
This way we are satisfying all build dependencies using apt-get system but also installing
the latest stable release of PIL. Some older versions of Ubuntu usually don't provide the
latest releases.

On RedHat/SciLinux:
# yum install python-imaging
# yum install freetype-devel
# pip install PIL

There's more...
There is a good online handbook, specifically, for PIL. You can read it at
http://www.pythonware.com/library/pil/handbook/index.htm, or download the
PDF version from http://www.pythonware.com/media/data/pil-handbook.pdf.

There is also a PIL fork, Pillow, whose main aim is to fix installation issues. Pillow can be found
at http://pypi.python.org/pypi/Pillow and it is easy to install.

On Windows, PIL can also be installed using a binary installation file. Install PIL in your Python
site-packages by executing .exe from http://www.pythonware.com/products/pil/.

Now, if you want PIL used in virtual environment, manually copy the PIL.pth file and the PIL
directory at C:\Python27\Lib\site-packages to your virtualenv site-packages directory.

13

www.it-ebooks.info
Preparing Your Working Environment

Installing a requests module


Most of the data that we need now is available over HTTP or similar protocol, so we need
something to get it. Python library requests makes that job easy.

Even though Python comes with the urllib2 module for work with remote resources and
supporting HTTP capabilities, it requires a lot of work to get the basic tasks done.

Requests module brings new API that makes the use of web services seamless and pain free.
Lot of the HTTP 1.1 stuff is hidden away and exposed only if you need it to behave differently
than default.

How to do it...
Using pip is the best way to install requests. Use the following command for the same:
$ pip install requests

That's it. This can also be done inside your virtualenv if you don't need requests for every
project or want to support different requests versions for each project.

Just to get you ahead quickly, here's a small example on how to use requests:
import requests
r = requests.get('http://github.com/timeline.json')
print r.content

How it works...
We sent the GET HTTP request to a URI at www.github.com that returns a
JSON-formatted timeline of activity on GitHub (you can see HTML version of that
timeline at https://github.com/timeline). After response is successfully read,
the r object contains content and other properties of the response (response code,
cookies set, header metadata, even the request we sent in order to get this response).

Customizing matplotlib's parameters in code


The Library we will use the most throughout this book is matplotlib; it provides the plotting
capabilities. Default values for most properties are already set inside the configuration file for
matplotlib, called.rc file. This recipe describes how to modify matplotlib properties from our
application code.

14

www.it-ebooks.info
Chapter 1

Getting ready
As we already said, matplotlib configuration is read from a configuration file. This file provides
a place to set up permanent default values for certain matplotlib properties, well, for almost
everything in matplotlib.

How to do it...
There are two ways to change parameters during code execution: using the dictionary of
parameters (rcParams) or calling the matplotlib.rc() command. The former enables us
to load already existing dictionary into rcParams, while the latter enables a call to a function
using tuple of keyword arguments.

If we want to restore the dynamically changed parameters, we can use matplotlib.


rcdefaults() call to restore the standard matplotlib settings.

The following two code samples illustrate previously explained behaviors:

Example for matplotlib.rcParams:


import matplotlib as mp
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.color'] = 'r'

Example for the matplotlib.rc() call:


import matplotlib as mpl
mpl.rc('lines', linewidth=2, color='r')

Both examples are semantically the same. In the second sample, we define that all
subsequent plots will have lines with line width of 2 points. The last statement of the
previous code defines that the color of every line following this statement will be red,
unless we override it by local settings. See the following example:
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 1.0, 0.01)

s = np.sin(2 * np.pi * t)
# make line red
plt.rcParams['lines.color'] = 'r'
plt.plot(t,s)

c = np.cos(2 * np.pi * t)
# make line thick

15

www.it-ebooks.info
Preparing Your Working Environment
plt.rcParams['lines.linewidth'] = '3
plt.plot(t,c)

plt.show()

How it works...
First, we import matplotlib.pyplot and NumPy to allow us to draw sine and cosine
graphs. Before plotting the first graph, we explicitly set line color to red using plt.
rcParams['lines.color'] = 'r'.

Next, we go to the second graph (cosine function), and explicitly set line width to 3 points
using plt.rcParams['lines.linewidth'] = '3'.

If we want to reset specific settings, we should call matplotlib.rcdefaults().

Customizing matplotlib's parameters per


project
This recipe explains where the various configuration files are that matplotlib uses, and why we
want to use one or the other. Also, we explain what is in these configuration files.

Getting ready
If you don't want to configure matplotlib as the first step in your code every time you
use it (as we did in the previous recipe), this recipe will explain how to have different default
configurations of matplotlib for different projects. This way your code will not be cluttered
with configuration data and, moreover, you can easily share configuration templates with
your co-workers or even among other projects.

How to do it...
If you have a working project that always uses the same settings for certain parameters in
matplotlib, you probably don't want to set them every time you want to add a new graph code.
Instead, what you want is a permanent file, outside of your code, which sets defaults for
matplotlib parameters.

matplotlib supports this via its matplotlibrc configuration file that contains most of the
changeable properties of matplotlib.

16

www.it-ebooks.info
Chapter 1

How it works...
There are three different places where this file can reside and its location defines its usage.
They are:

ff Current working directory: This is where your code runs from. This is the place to
customize matplotlib just for your current directory that might contain your current
project code. File is named matplotlibrc.
ff Per user .matplotlib/matplotlibrc: This is usually in user's $HOME directory (under
Windows, this is your Documents and Settings directory). You can find out
where your configuration directory is using the matplotlib.get_configdir()
command. Check the next command.
ff Per installation configuration file: This is usually in your python site-packages.
This is a system-wide configuration, but it will get overwritten every time you reinstall
matplotlib; so it is better to use per user configuration file for more persistent
customizations. Best usage so far for me was to use this as a default template if
I mess up my user's configuration file or if I need fresh configuration to customize
for a different project.

The following one-liner will print the location of your configuration directory and can be run
from shell.
$ python -c 'import matplotlib as mpl; print mpl.get_configdir()'

The configuration file contains settings for:

ff axes: Deals with face and edge color, tick sizes, and grid display.
ff backend: Sets the target output: TkAgg and GTKAgg.
ff figure: Deals with dpi, edge color, figure size, and subplot settings.
ff font: Looks at font families, font size, and style settings.
ff grid: Deals with grid color and line settings.
ff legend: Specifies how legends and text inside will be displayed.
ff lines: It checks for line (color, style, width, and so on) and markers settings.
ff patch: Patches are graphical objects that fill 2D space, such as polygons and circles;
set linewidth, color, antialiasing, and so on.
ff savefig: There are separate settings for saved figures. For example, to make
rendered files with a white background.
ff text: This looks for text color, how to interepret text (plain versus latex markup)
and similar.
ff verbose: It checks how much information matplotlib gives during runtime: silent,
helpful, debug, and debug-annoying.
ff xticks and yticks: These set the color, size, direction, and labelsize for major and
minor ticks for x and y axes.

17

www.it-ebooks.info
Preparing Your Working Environment

There's more...
If you are interested in more details for every mentioned setting (and some that we did
not mention here), the best place to go is the website of matplotlib project where there is
up-to-date API documentation. If it doesn't help, user and development lists are always
good places to leave questions. See the back of this book for useful online resources.

18

www.it-ebooks.info
Knowing Your Data
2
In this chapter we will cover the following recipes:

ff Importing data from CSV


ff Importing data from Microsoft Excel files
ff Importing data from fixed-width datafiles
ff Importing data from tab-delimited files
ff Importing data from a JSON resource
ff Exporting data to JSON, CSV, and Excel
ff Importing data from a database
ff Cleaning up data from outliers
ff Reading files in chunks
ff Reading streaming data sources
ff Importing image data into NumPy arrays
ff Generating controlled random datasets
ff Smoothing the noise in real-world data

Introduction
This chapter covers basics about importing and exporting data from various formats. Also
covered are ways of cleaning data, such as normalizing values, adding missing data, live data
inspection, and usage of some similar tricks to get data correctly prepared for visualization.

www.it-ebooks.info
Knowing Your Data

Importing data from CSV


In this recipe we will work with the most common file format that one will encounter in the
wild world of data, CSV. It stands for Comma Separated Values, which almost explains all
the formatting there is. (There is also a header part of the file, but those values are also
comma separated.)

Python has a module called csv that supports reading and writing CSV files in various
dialects. Dialects are important because there is no standard CSV and different applications
implement CSV in slightly different ways. A file's dialect is almost always recognizable by the
first look into the file.

Getting ready
What we need for this recipe is the CSV file itself. We will use sample CSV data that you can
download from ch02-data.csv.

We assume that sample datafiles is in the same folder as the code reading it.

How to do it...
The following code example demonstrates how to import data from a CSV file. We will:

1. Open the ch02-data.csv file for reading.


2. Read the header first.
3. Read the rest of the rows.
4. In case there is an error, raise an exception.
5. After reading everything, print the header and the rest of the rows.
import csv

filename = 'ch02-data.csv'

data = []
try:
with open(filename) as f:
reader = csv.reader(f)
header = reader.next()
data = [row for row in reader]
except csv.Error as e:
print "Error reading CSV file at line %s: %s" % (reader.line_
num, e)
sys.exit(-1)

20

www.it-ebooks.info
Chapter 2
if header:
print header
print '=================='

for datarow in data:


print datarow

How it works...
First, we import the csv module in order to enable access to required methods. Then, we
open the file with data using the with compound statement and bind it to the object f. The
context manager with statement releases us of care about the closing resource after we are
finished manipulating those resources. It is a very handy way of working with resource-like
files because it makes sure that the resource is freed (for example, that the file is closed)
after the block of code is executed over it.

Then, we use the csv.reader() method that returns the reader object, allowing us to
iterate over all rows of the read file. Every row is just a list of values and is printed inside
the loop.

Reading the first row is somewhat different as it is the header of the file and describes the
data in each column. This is not mandatory for CSV files and some files don't have headers,
but they are a really nice way of providing minimal metadata about datasets. Sometimes
though, you will find separate text or even CSV files that are just used as metadata,
describing the format and additional data about the data.

The only way to check what the first line looks like is to open the file and visually inspect it
(for example, see the first few lines of the file). This can be done efficiently on Linux using
bash commands such as head as follows:
$ head some_file.csv

During iteration of data, we save the first row in header, while we add every other row to the
data list.

Should any errors occur during reading, csv.reader() will generate an error that we can
catch and print the helpful message to the user, in order to help detection of errors.

There's more...
If you want to read about the background and reasoning for the csv module, the PEP-defined
document CSV File API is available at http://www.python.org/dev/peps/pep-0305/.

If we have larger files that we want to load, it's often better to use well-known libraries, such
as NumPy's loadtxt(), that cope better with large CSV files.

21

www.it-ebooks.info
Knowing Your Data

The basic usage is simple as shown in the following code snippet:


import numpy
data = numpy.looadtxt('ch02-data.csv', dtype='string', delimiter=',')

Note that we need to define a delimiter to instruct NumPy to separate our data as
appropriate. The function numpy.loadtxt() is somewhat faster than the similar function
numpy.genfromtxt(), but the latter can cope better with missing data, and you are able
to provide functions to express what is to be done during the processing of certain columns
of loaded datafiles.

Currently, in Python 2.7.x, the csv module doesn't support Unicode, and you
must explicitly convert the read data into UTF-8 or ASCII printable. The official
Python CSV documentation offers good examples on how to resolve data
encoding issues.
In Python 3.3 and later versions, Unicode support is default and there are no
such issues.

Importing data from Microsoft Excel files


Although Microsoft Excel supports some charting, sometimes you need more flexible and
powerful visualization and need to export data from existing spreadsheets into Python for
further use.

A common approach to importing data from Excel files is to export data from Excel into
CSV-formatted files and use the tools described in the previous recipe to import data using
Python from the CSV file. This is a fairly easy process if we have one or two files (and have
Microsoft Excel or OpenOffice.org installed), but if we are automating a data pipe for many
files (as part of an ongoing data processing effort), we are not in a position to manually
convert every Excel file into CSV. So, we need a way to read any Excel file.

Python has decent support for reading and writing Excel files through the project
www.python-excel.org. This support is available in the form of different modules
for reading and writing, and is platform independent; in other words, we don't have to
run on Windows in order to read Excel files.

The Microsoft Excel file format changed over time, and support for different versions is
available in different Python libraries. The latest stable version of XLRD is 0.90 at the
time of this writing and it has support for reading .xlsx files.

22

www.it-ebooks.info
Discovering Diverse Content Through
Random Scribd Documents
Athenian citizens were not allowed to marry foreign women, even
of reputation and virtue; this law was not strictly observed: the
penalty for the violation of it was fixed at one thousand drachms.
Simo mentions the epithet peregrina, as what Chremes said he had
heard Glycera called; but does not himself drop the slightest hint
against her, but, on the contrary, praises her modest demeanour; as
he must have been well aware, that she did not deserve such an
epithet, being her opposite neighbour, and having seen her abroad:
ξέναι, or strange women, when they appeared in public, were
obliged to wear striped dresses, to distinguish them from women of
innocent conversation.

NOTE 83.

Of a wicked mind, one can expect nothing but wicked intentions.


In the Latin, mala mens, malus animus. It is not easy to
discriminate with accuracy the different meanings the Romans
attached to mens and animus. Some think that animus meant the
heart, and mens the faculty of thinking. Grotius has, in this passage,
taken those words to signify conscience and judgment: but, I think it
probable, that the word animus was usually employed when they
spoke of the soul, and that mens was intended to express what we
understand by the word mind, when we speak of greatness of mind,
or littleness of mind. Animus was, perhaps, about equivalent to that
elegant expression,—instinctus divinitatis.

NOTE 84.

Exit Sosia.
“Here we take our last leave of Sosia, who is, in the language of
the commentators, a protatick personage, that is, as Donatus
explains it, one who appears only once in the beginning (the
protasis) of the piece, for the sake of unfolding the argument, and is
never seen again in any part of the play. The narration being ended,
says Donatus, the character of Sosia is no longer necessary. He
therefore departs, and leaves Simo alone to carry on the action. With
all due deference to the ancients, I cannot help thinking this method,
if too constantly practised, as I think it is in our author, rather
inartificial. Narration, however beautiful, is certainly the deadest part
of theatrical compositions: it is, indeed, strictly speaking, scarce
dramatic, and strikes the least in the representation: and the too
frequent introduction of a character, to whom a principal person in
the fable is to relate in confidence the circumstances, previous to the
opening of the play, is surely too direct a manner of conveying that
information to the audience. Every thing of this nature should come
obliquely, fall in a manner by accident, or be drawn as it were
perforce, from the parties concerned, in the course of the action: a
practice, which, if reckoned highly beautiful in epic, may be almost
set down as absolutely necessary in dramatic poetry. It is, however,
more adviseable, even to seem tedious, than to hazard being
obscure. Terence certainly opens his plays with great address, and
assigns a probable reason for one of the parties being so
communicative to the other; and yet it is too plain that this narration
is made merely for the sake of the audience, since there never was a
duller hearer than Master Sosia, and it never appears, in the sequel
of the play, that Simo’s instructions to him are of the least use to
frighten Davus, or work upon Pamphilus. Yet even this protatick
personage is one of the instances of Terence’s art, since it was often
used in the Roman comedy, as may be seen even in Plautus, to
make the relation of the argument the express office of the
prologue.”—Colman.
Monsieur Baron does not dismiss Sosia here, but brings him on
the stage again; once in the third act, and once in the fourth. Sir R.
Steele introduces Humphrey again in the first act, and also in the
fifth. We are told by Donatus, that in the Andrian and Perinthian of
Menander, which are similar in the plot, the first scene is the same as
in Terence, but that in the Perinthian, the old man consults with his
wife instead of Sosia; and, in the Andrian he opens with a soliloquy.
NOTE 85.

But, here he comes.


It has been objected against many dramatic writers, that they are
guilty of great neglect in first bringing their characters on the stage,
without preparing the audience for their appearance, and
acquainting them with their names; and sometimes it happens that
an actor has been on the stage a considerable time, before the
audience know whom he is meant to personate. Terence’s art is
admirably shown in this particular; a new character scarcely ever
appears on the stage after the first scene, before his name, and
character, and perhaps what he may be expected to say or do, is
announced to the audience. For example, in the Andrian, Act I.
Scene I., Simo describes the occupation and character of Davus
before he appears; and names him to the audience as he comes on
the stage. In Act I. Scene III., Davus introduces Mysis: in Act I.
Scene IV., Mysis prepares the audience for the appearance of
Pamphilus: in Act III. Scene IV., Simo announces Chremes, and
Mysis is the nomenclator of Crito in the last scene of the fourth Act.
This rule of preparation for the next scene was called, among the
ancients, παρασκευὴ.

NOTE 86.

How this rascal prates!


Carnifex quæ loquitur. Carnifex, or carnufex, means literally an
executioner: this was one of the most opprobrious epithets used by
the Romans. Of all their public servants, the carnifex was the lowest
in rank: his office extended only to crucifixion, which was never
inflicted in Rome on any but those who were considered as the very
worst of criminals. The person of the carnifex was held in such
abhorrence, that he was never suffered to reside in Rome, and rarely
(though sometimes) permitted to enter the city. Vide Cicero’s Oration
for Rabirius. Carnifex means literally a butcher; and most of the
writers of later ages have used it in that sense.

NOTE 87.

No: I am not Œdipus, but Davus.


This is as much as to say, I am a plain man, I am no reader of
riddles: because Œdipus, king of Thebes, was particularly celebrated
for solving an enigma, which had long baffled the penetration of all
the Thebans. Ancient writers relate the story thus: Europa, the sister
of Cadmus, the first king of Thebes, having been carried off by
Jupiter; Juno, in her jealousy, wreaked her vengeance on Europa’s
family, and persecuted Cadmus and his descendants with the most
inveterate hostility. During the reign of Creon, one of the successors
of Cadmus, Juno sent to destroy Thebes, a dreadful monster, called
Sphinx, which was described as having the face and voice of a
woman, the wings of a dragon, the body of a dog, and the claws of
a lion. This extraordinary monster dwelt in a cave, immediately in the
neighbourhood of Thebes, and seizing every one that ventured to
approach, proposed the following well-known riddle, “What walks in
the morning on four legs, at noon on two, and at night on three?”
Those who were unable to solve the enigma were instantly torn in
pieces; and, as the Thebans were, in general, so remarkable for their
slowness and sluggishness, that they were called “Theban pigs” by
the rest of Greece, it may be readily believed that the monster’s
question long remained unanswered. When the city was in danger of
total demolition, Creon the king offered his daughter Jocasta, and his
crown, to him who should solve the riddle, as the oracle declared
that to be the only means of deliverance. This was at last
accomplished by Œdipus, who replied, that it was man: who crawls
in his childhood, walks upright in the vigour of his age, and who uses
a crutch when he grows old: on hearing this answer, the Sphinx slew
herself.
Some commentator on Terence very ingeniously observes, that
Davus, by saying that he is not Œdipus, and cannot understand his
riddle, covertly insinuates that Simo is a second Sphinx.

NOTE 88.

The grinding-house.
Terence has rendered by the word pistrinum, the Greek
σωφρονιστήριον, or house of correction, whither criminals were sent
for the various terms of imprisonment proportioned to their offences.
Slaves, while in this prison, were employed chiefly in grinding corn,
which, from a deficiency of mechanical knowledge, was, in those
times, a very laborious employment. The Athenians, who were
universally celebrated for their kind and gentle treatment of slaves,
were very reluctant to proceed to severer punishments than
whipping or imprisonment: but when a flagrant delinquency
rendered it necessary to make an example, they either burned the
criminal with a hot iron, in the offending member, if possible; or put
on his feet a torturing instrument, called χοῖνιξ. If the law required
the criminal to suffer death, which happened in very few cases, he
was either hung, beaten to death with clubs, or cast into a deep pit,
called βάραθρον, filled at the bottom with sharp spikes. They
sometimes had recourse to other extraordinary modes of
punishment: but the before-mentioned were the most common.

NOTE 89.

In truth, friend Davus, from what I have just heard.


This scene contains the second part of the narration, which
possesses all the requisites enumerated by Cicero, perspicuity,
probability, brevity, and sweetness. It is introduced with Terence’s
usual art, and enough is said respecting Glycera’s birth, to prepare
the mind for the dénouement in the last act. This scene, and that
before it, are omitted in the Conscious Lovers; and a dialogue
between Humphrey and Tom, and another between Tom and Phyllis,
the English Davus and Mysis, are substituted instead of them: but
Phyllis is the servant of Lucinda, the lady Sir J. Bevil wishes his son
to marry: and not of Indiana, the modern Glycera. The two scenes
above mentioned contain only one incident: the conveyance of a
letter from young Bevil to Lucinda, apprizing her of his disinclination
to the match.

NOTE 90.

This affair must be handled dexterously, or either my young master


or I must be quite undone.
The original of this passage is as follows: Quæ si non astu
providentur, me, aut herum pessundabunt. A deviation from the
customary mode of expression sometimes occurs in our author’s
writings. I shall set down the most remarkable words of this nature
that are to be found in this play.

Abutor, with an accusative.


Alterco, for altercor.
Astu, for Astutia.
Complacita est, for placuit.
Catus.
Claudier, for claudi.
Conflictatur, cum ingeniis ejusmodis.
Duint, for dent.
Diecula.
Emergere se, for emergere.
Face, for fac.
Introspicere.
Ipsus.
Immutarier, for immutari.
Morigera.
Maximum facere hominem, for maximi.
Ornati, for ornatus.
Preci, for precibus.
Postillà, for posteà.
Symbola, for symbolum.
Spero, for timeo.
Subsarcinatam.
Tetulit.
Tumulti, for tumultus.

NOTE 91.

If he finds out the least thing I am undone.


Terence has the art of making us feel interested in the favour of
almost all his characters: they insensibly gain ground in our good
opinion: even this Davus, who certainly has a spice of the rogue
about him, creates a warm interest in his favour by his fidelity to
Pamphilus; and his generosity in risking his own safety to serve him:
he braves the threats of Simo, when, by assisting him, and betraying
Pamphilus, he must have secured the old man’s favour, and
consequently great advantages to himself. But very few of the worst
characters in Terence’s plays seem to us to be wholly unamiable.

NOTE 92.

I think their intentions savour more of madness than of any thing


else.
Terence plays upon the words in the original of this passage,
which is as follows,
“Nam inceptio est amentium, haud amantium.”
Literally, For they act like mad people, not like lovers. This pun
cannot be preserved in an English translation, till two words can be
found alike in sound, one meaning “mad people,” and the other
“lovers.” The only attempt in English is the following: but the author
has rather altered the sense.

“For they fare as they were lunaticke, and not lovesicke.”


Bernard.

Terence plays upon words in this manner several times in this


play,

Maledicere, malefacta ne noscant sua.


Solicitando, et pollicitando eorum animos lactas.
Quia habet aliud magis ex sese, et majus.
Quo jure, quaque injuria.
Ipsu’ sibi esse injurius videatur, neque id injuriâ.
P. Quid vis patiar? D. Pater est Pamphile.

The ancients manifested very great partiality for this species of


wit, which the Greeks called παρανομασία and the Romans
agnominatio. The writings of Plautus abound with puns above all
others, and he is thought to have applied them with great ingenuity:
the following may serve as a specimen.

Boius est, Boiam terit.


Advenisse familiares dicito.
Nescio quam tu familiaris es: nisi actutum hinc abis,
Familiaris, accipiere faxo haud familiariter
Optumo optumè optumam operam das.

Though the Greeks and Romans considered puns an ornament to


writings and discourses of all kinds, modern critics have decided that
they ought to be admitted only in writings of a light nature; and that
they decrease the force and beauty of grave and serious
compositions, which ought to wear an air of dignified sublimity,
unmixed with any thing of a trivial nature.
The lines immediately preceding the before-mentioned passages
are thus altered by a French editor. Vide Note 72.

Ad hæc mala hoc etiam mihi accedit; hæc Andria,


Quam clam patre uxorem duxit Pamphilus, gravida ab eo est.

The original lines are,

Ad hæc mala hoc etiam mihi accedit; hæc Andria,


Sine ista uxor, sine amica est gravida a Pamphilo est.

NOTE 93.

Boy or girl, say they, the child shall be brought up.


In the Latin,
Quidquid peperisset decreverunt tollere.
Boy or girl, they have resolved that it shall be taken up. The
words taken up allude to the custom which prevailed in Greece, of
destroying children. This barbarous cruelty was practised on various
pretences; if an infant was, at its birth, deformed in any of its
members, or if it appeared extremely feeble or sickly, the laws
allowed, and even enjoined, that it should be exposed: sometimes
illegitimacy was considered a sufficient cause for the exposure of a
child. Though the parents were generally allowed to choose whether
their offspring should be destroyed or preserved; in some parts of
Greece all the inhabitants were compelled to send their new-born
infants to officers appointed to examine them: who, if they found
them not robust and healthy, cast them immediately into deep
caverns, called ἀποθέται, which were dedicated to this purpose. It
was customary, in Athens, to place a new-born infant on the ground
at the feet of its father, if he then took it up in his arms, it was
considered that he bound himself to educate and provide for the
child: hence, the expression tollere, to take up: but, if on the
contrary, he refused to acknowledge it, a person appointed for that
purpose conveyed it to some desert place at a distance from the city:
and there left it to perish. The Thebans are said to have been the
only people in Greece, among whom this barbarous custom did not
prevail: but the story of Œdipus, a prince who was exposed, though
afterwards preserved, is a proof that they did not altogether abstain
from this practice.

NOTE 94.

To prove that she is a citizen of Athens.


Women were allowed to enjoy the privileges of Athenian citizens,
and, at the building of Athens, by Cecrops, they carried a point of no
less importance than the choice of a name for the new city, in
opposition to the votes of the men. Varro tells us that Neptune
wished the new-built city to be called after his name, and that
Athena, or Minerva, rivalled his pretensions. The question being put
by Cecrops to his people, the men all voted for Neptune, but the
women voted for Minerva, and gained, by one vote, the privilege of
naming the city. The women were wholly excluded from any share in
the government of Athens, in later ages; though they still retained
various privileges as Athenian citizens.
For a further explanation of the rights of the Athenian citizens;
and for some account of the city of Athens, vide Notes 150, 179,
180, 181, 193, 197.

NOTE 95.

Once upon a time, a certain old merchant.


The title of merchant we are to suppose to be added by Davus to
embellish the tale. Neither Chremes nor Phania are described as
merchants. This addition is well managed by the author, as Davus,
who thought the whole a fabrication, imagined he was more likely to
gain credit by telling the tale that way; as a considerable traffick was
carried on between Athens and the island of Andros, which was a
very fertile spot.
M. Baron has translated this scene with great fidelity and beauty.
Davus developes in it a plan to break off the dreaded match with
Philumena, by introducing Glycera to Chremes: which incident is
substituted instead of the birth of the child. There is a break in the
French lines which renders them inimitably beautiful.
“De ce vieillard fougueux pour calmer la furie,
Quoi! Ne pourrions nous pas résoudre Glycérie
A venir à ses pieds lui demander——? Helas!
Glycérie est malade, et je n’y songe pas.”
Baron.

NOTE 96.

Well, I’ll betake myself to the Forum.


A forum, both in Athens and Rome, was a large open space within
the city, dedicated to various purposes. The forum was a place
where the people met for public worship, for the administration of
justice, and to debate on the public affairs. In the Forum, also, were
the temples, hospitals, sanctuaries, and the markets of all kinds: in
short, it was a place of general rendezvous for men of all ranks and
professions, and was, in many respects, very similar to those places
of meeting we call by the name Exchange.
In Rome there were six great forums, 1. the Roman, 2. the Julian,
3. the Augustan, 4. the Palladian, 5. the Trojan, 6. the Forum of
Sallust. In Athens, the principal Forum was called ἀρχαία ἀγορὰ; it
was extremely spacious, and decorated with some very fine
buildings, and statues of eminent persons. There were also many
others, but the most considerable was called the Forum, by way of
distinction.

NOTE 97.

Act I. Scene IV.


Of all writers ancient or modern, except Seneca, Terence was the
most indefatigable in endeavouring to embellish his writings with all
the ornaments that alliteration could give them. It is not my
intention to enter in this place into a discussion of the advantages,
or disadvantages that verses may derive from alliteration; a subject
on which critics differ as widely as they can on any other point. The
practice of many first-rate writers, however, both ancient and
modern, who have thought that alliteration adorned their
compositions, entitles it to attention. Although eminent critics have
argued against this literary ornament, that its success is but a trivial
excellence, I cannot but remark that it is allowed on all sides that
great labour, care, and patience, are requisite, to succeed in
alliteration; which must certainly contribute to render it of some
value, and afford an absolute proof of the excessive labour and
deliberation with which Terence wrote his plays, every line of which
was, as I may say, weighed, before he wrote it down: for no author,
ancient or modern, (with the before-mentioned exception,) ever
employed alliteration so frequently, nor, in my opinion, with better
effect than Terence.
The following lines will afford the reader a specimen of the almost
astonishing extent to which alliteration was used by some of the
ancient authors, Greek and Latin.

I. From Terence.

“Audivi, Archillis, jamdudum: Lesbiam adduci jubes


Sane pol illa temulenta est mulier, et temeraria
Nec sati digna cui committas primo partis mulierem.
Tamen eam adducam. Importunitatem spectate aniculæ;
Quia compotrix ejus est. Diana da facultatem, obsecro,
Huic pariundi, atque illi in alius potius peccandi locum.
Sed, quidnam Pamphilum exanimatum video? vereor quid siet.
Opperiar, ut sciam, numquidnam hæc turba tristitiæ adferat.
Ut animum ad aliquod stadium adjungant, aut equos—
Alere, aut canes ad venandum, aut ad philosophos.
In ignem imposita est. Fletur. Interea hæc soror.
Mala mens, malus animus. Quem quidem ego si sensero.
Ipsum animum ægrotum ad deteriorem partem plerumque applicat,
Nec, quid agam, cerium est; Pamphilumne adjutem, an auscultem
seni.
Facite, fingite, invenite, efficite, qui detur tibi.
Aliquot me adiere, ex te auditum qui aiebant.
Quid isthuc? si ita isthuc animum induxti esse utile,
Mala ingeram multa? Atque aliquis dicat, nihil promoveris.
Multum, Molestas certe ei fuero, atque animo morem gessero.
Quibu’ quidem quam facile poterat quiesci, si hic quiesset.
Age, si hic non insanit satis suà sponte, instiga.
Ausculta. Audivi jam omnia. Anne tu omnia?
Audivi inquam a principio. Audistin’?
————-optavit parare hic divitias,
Potius quam in patria honeste pauper vivere.
Sati’ jam sati’ Simo, spectata.
In alio occupato amore, abhorrenti ab re uxoriâ.
Pro peccato magno paulum supplicii satis est patri.
Nam hunc scio mea solide solum gavisurum gaudia.
Solus est quem diligunt Di. Salvus sum si hæc veca sunt.”

II. From Seneca.


“Meleagre, matris
Impius mactas; morerisque dextra
Matris iratae meruere cuncti
Morte quod.”

Accingere, anime; bella non levia apparas.

Servate sontem saxeo inclusum specu.

Pastor triformis littoris Tartessii.


Peremptus, acta est præda ab occasu ultimo
Notum Cythæron pavit Oceano pecus.
Penetrare jussus solis æstivi plagas.
Conquesta domum: licet ipse velit
Clarus niveos inter olores,
Istrum cygnus Tanaimque colens,
Extrema loqui; licet Alcyones
Ceyca suum fluxu leviter.
Plangente sonent, cum tranquillo
Male confisae credunt interum.
Obliquatque; oculos, oraque.
Tandemque venias victor ad victam domum.

III. From Cicero.


De scripto dicta sententia est, quam Senatus frequens secutus est
summo studio magnoque consensu.

IV. From Pliny.


Cum sciam, Domine, ad testimonium laudemque morum meorum,
pertinere tam boni principis judicio exornari, rogo, dignitati, ad quam
me provexit indulgentia tua, vel auguratum, vel septemviratum, quia
vacant, adjicere digneris: ut jure sacerdotii precari deos pro te
publicè possim, quos nunc precor pietate privatâ.

V. From Horace.

Acriter elatrem, pretium ætas altera sordet.


Ambigitur.

VI. From Ovid.

Se cupit imprudens. Et qui probat ipse probatur.


Dumque petit, petitur; pariterque.
VII. From Plutarch.

Κόσμος ἐστιν ὡς ἔλεγε Κράτης, τὸ Κοσμοῦν. Κοσμεῖ δὲ τὸ


Κοσμιώτερον.

VIII. From Tyrtæus.

Ἡ δ’ Ἀρετὴ τόδ’ Ἄεθλον ἐν Ἀνθρώποισιν Ἄριστον.

IX. From Æschines.

Οἱ Ἐξ Ἐκείνου Ἔχοντες Ἐν τῇ οἰκίᾳ.

ΤαῦΤα μὲν οὖν μοι δοκῶ καὶ Τἄλλα Τὰ ΤούΤοις.

Ἔοικε, Φειδίας Ἐνεργολαβεῖν Εἰργάσατο καὶ Ἐνεπιορκεῖν.

X. From Anacreon.

Τί Μοι, τί Μοι γόων,


Τί Μοι Μέλει Μεριμνῶν.

Μέσον, ναῒ
ΦορήΜεθα σὺν Μελαίνᾳ,
ΧειΜῶνι Μοχθεῦντες Μεγάλῳ.

NOTE 98.

However, I’ll bring her.


Mr. Cooke makes this speech come from Archillis, and writes it
thus: Tamen eam adduce, I say, fetch her. This reading is taken
from Guyetus: but Dr. Bentley objects to Archillis within calling to
Mysis without. But as Mysis uses the expression importunitatem
spectate aniculæ, see the old woman’s importunity, and not audite
importunitatem, hear, &c.: we must suppose Archillis to show her
impatience by gestures, as she stood at the door of Glycera’s house.

NOTE 99.

Mark, how importunate this old baggage is.


Importunitatem spectate aniculæ. Anicula is a word of singular
derivation, and signifies literally a sorceress; being compounded of
two Latin words, one signifying an old woman, and the other to
howl: because sorceresses always howled when they made their
incantations. We must not suppose that Mysis here meant to call
Archillis a sorceress, but merely used the word above mentioned as
a term of reproach. According to Antonius Magnus, the aniculæ were
not a little mischievous, as he proposes to shew by the following
quotation: “Retulit Leonardus Varius, lib. I. de Fascino, multas hac
nostra tempestate existere aniculas, quarum impuritate non paucos
effascinari pueros, illosque non modo in gravissimum incidere
discrimen, verum atque acerbam sæpissime subire mortem. Pecudes
insuper partu, et lacte privari, equos macrescere, et emori, segetes
absque fructu colligi, arbores arescere, ac denique omnia pessum iri
quandoque videri.”—Antonius Magnus. Perscrutator rerum abditarum
naturæ. Norimberga, 1681, p. 39.

NOTE 100.

Well, may Diana grant my poor mistress, &c.


The common reading of this passage is, Di date facultatem, May
the Gods grant, &c., but I should rather imagine that Terence wrote,
Diana da facultatem, May Diana grant, &c., because, on these
occasions, the Greeks never invoked the assistance of all the gods,
but usually requested the help of Diana, as Glycera does afterwards,
when she calls upon her by the name of Juno Lucina, (vide Note
143). Diana was supposed to preside over women in childbirth, and
was called Εἰλείθυια.

NOTE 101.

A. I. S. V. Pamphilus, Mysis.
This scene contains the third and last part of the narration, which
is entirely pathetic, and its length is very artificially and successfully
relieved by the figure called by the Greeks προσωποποια, which is
introduced with so many moving and pathetic graces, as afford
ample proof that Terence was as great a master of the passions, as
even Trabea, Attilius, and Cæcilius themselves, who were so highly
extolled by the ancients for their excellence in compositions of that
nature. Terence has admirably relieved the necessary length of his
narration in this play, by his judicious method of dividing it: the first
part is serious, (vide Note 65,) and raises our curiosity: the second
part is comic, (vide Note 89,) and excites our laughter; the third part
is pathetic, and moves our pity. The lines in which Pamphilus
describes the death of Chrysis are so extremely moving, that some
of the most eminent critics have considered them at least equal, if
not superior, to all attempts in the pathetic both ancient and
modern. The finest passage in M. Baron’s Andrienne is, (in my
opinion,) his imitation of the before-mentioned speech of Pamphilus:
and the inimitable beauty which so much strikes us in the French
copy ought to impress us with a just idea of the splendid merit of
the Latin original.
The whole speech is too long to be inserted here, the following
are extracts:

“Si je m’en souviendrai! Qui? moi? Toute ma vie.


Ce que me dit Chrysis parlant de Glicérie,
Elle me dit, (Misis j’en verse encore des pleurs.)
Elle est jeune, elle est belle, elle est sage, et je meurs.
Je vous conjure donc par sa main que je tiens;
Par la foi, par l’honneur, par mes pleurs, par les siens;
Par ce dernier moment qui va finir, ma vie,
De ne vous séparer jamais de Glicérie.
Elle prit nos deux mains, et les mit dans la sienne:
Que dans cette union l’amour vous entretienne;
C’est tout.—Elle expira dans le même moment.
Je l’ai promis, Misis, je tiendrai mon serment.”
Andrienne, A. I. S. VII.

NOTE 102.

And why has Chremes changed his mind.

“Id mutavit, quoniam me immutatum videt.”


The verb immutare in other Latin authors, and even in other parts
of Terence himself, signifies to change; as in the Phormio, Antipho
says, Non possum immutarier. I cannot be changed. But here, the
sense absolutely requires that immutatum should be rendered not
changed. Madame Dacier endeavours to reconcile this, according to
a conjecture of her father’s, by shewing that immutatum stands for
immutabilis, as immotus for immobilis, invictus for invincibilis, &c.
But these examples do not remove the difficulty; since those
participles always bear a negative sense, which immutatus does not:
and thence arises all the difficulty. Terence certainly uses the verb
immutare both negatively and positively, as is plain from this
passage, and the above passage in the Phormio: and I dare say,
with strict propriety. In our own language, we have instances of the
same word bearing two senses, directly opposite to each other. The
word let, for instance, is used in the contradictory meanings of
permission and prohibition. The modern acceptation of the word is
indeed almost entirely confined to the first sense; though we say,
even at this day, without let or molestation. Shakspeare, in Hamlet,
says,
‘I’ll make a ghost of him that lets me;’
“That is, stops, prevents, hinders me, which is directly opposite to
the modern use of the word.”—Colman.
“Immutare always signifies to change, immutatus therefore
cannot mean unchanged: we see, moreover, that Pamphilus has
been all along in love with Glycera, and that he never for a moment
entertained the slightest idea of forsaking her. This passage was very
difficult; but my father has made it easy, by shewing that immutatus
is put for immutabilis, and that composed adjectives, which are
derived from passive participles, do not always express what is done,
but sometimes what may be done; that is to say, they become
potentials. For example, immotus for immobilis, infectus for what
cannot be done, invictus for invincibilis, invisus for invisibilis,
indomitus for indomabilis, thus immutatus is for immutabilis.”—
Madame Dacier.
The reader will judge whether the arguments used by these two
learned and ingenious critics, will justify them in translating
immutatus in a sense directly opposite to its usual meaning, in the
writings of Cicero, and the most learned of the Roman authors. With
all the respect which is unquestionably due to the pre-eminent
talents of Madame Dacier and Mr. Colman, I am inclined to believe
that the sense of this passage is made more clear by the reading I
have adopted. If we allow their arguments to be of force, we must
translate the sentence thus, is Chremes changed because he sees
that I am unchanged. But if we allow immutatus to retain its usual
signification, the sentence must be read thus, is he changed because
he sees that I am changed: i. e., because I, who had so high a
character for prudence, am changed, and by my connexion with
Glycera have proved that I am imprudent. It is, in short, as if he
said, Chremes has changed his mind once on account of my
connexion with Glycera, and now, I suppose, he changes it again for
the same wise reason. This would not, (in my opinion,) be an
unnatural expression for an impatient man: and the sequel of the
same speech seems to favour this interpretation.

NOTE 103.
I shrewdly suspect that this daughter of Chremes is either
hideously ugly, or that something is amiss in her.
In the Latin aliquid monstri alunt, they breed up some monster.
This expression took its rise from the custom of exposing and
destroying monstrous and deformed children, (see Note 93) which
was required by law: therefore, those parents who resolved,
notwithstanding, to educate a child of that kind, were compelled to
do so with the utmost secrecy: hence, the phrase “alere monstrum,”
to breed up a monster, was used in Rome, to express any thing
done in great secrecy. Terence has, by no means, violated
probability, in representing Pamphilus as unacquainted with the
person of Philumena: though she had been contracted to him; as
Grecian women very seldom appeared abroad, and never, unveiled:
and it not unfrequently occurred, that the bridegroom was
introduced to the bride for the first time on the day of marriage.

NOTE 104.

She is in labour.
In the Latin, Laborat e dolore. Cooke thinks that these words
mean merely she is weighed down by grief: and argues, that if
Pamphilus had understood her words in any other sense, he would
have urged her to more haste; as he does, when she tells him that
she is going for a midwife. But laboro sometimes means to strive or
struggle, as in Ovid,

“Et simul arma tuli, quæ nunc quoque ferre laboro.”


Metam., B. XIII. L. 285.
’Twas then I bare
Achilles’ arms, which now I strive to wear.

Also, in Horace,

———————“laborat
Lympha fugax trepidare.”
Od., B. II. O. 3. L. 11.

The rushing water strives


To force a swifter passage.

And that, doubtless, is its meaning, when joined to dolore. What


Mysis says, moreover, to Lesbia the midwife, in the first scene of the
third act, is sufficient to justify this interpretation.

NOTE 105.
Can I suffer, that she, who has been brought up in the paths
of modesty and virtue, should be exposed to want, and,
perhaps, even to dishonour?
By the expression sinam coactum egestate ingenium immutarier?
shall I suffer her innocence to be endangered by want? I am inclined
to believe that Terence meant, the want of friends and protection,
and not poverty, because we are told afterwards, (Act IV.) that
Glycera was possessed of the property of Chrysis, which we are to
imagine, from what Crito says concerning it, to have been something
considerable. I believe egestate is often put for want of any kind. It
may appear somewhat enigmatical, that Terence should speak of the
liberal and virtuous education of Glycera, by such a person as
Chrysis was said to have been; but it is a circumstance in no wise
repugnant to the manners of the Greeks; as we see in the Eunuch in
the instance of Thais and Pamphila.
NOTE 106.
I call upon you, then, by the pledge of this hand you now
extend to me, and by the natural goodness of your
disposition.
Quod ego te per hanc dextram oro, et ingenium tuum. Some read
genium, by your genius, or by your good angel, and quote the
following passage from Horace in support of this reading:

“Quod te per genium dextramque, deosque penates


Obsecro et obtestor.”
Epistles, B. I. E. 7. L. 94.

The difference, however, between the genius and the ingenium, is


not very material; as the ingenium or disposition, was supposed by
the ancients to be prompted by the genius, or tutelar spirit, who
presided over and directed all the actions of mankind. Each person
was thought to have a good and also an evil spirit, who never
quitted its charge till death: the spirits attendant on the men were
called by the Romans genii, and those belonging to the women were
named junones. The Greeks considered these aërial beings as of a
nature between that of gods and men: and that they communicated
to the latter the will of the former by oracles, dreams, &c. Apuleius
takes the genius to be the same as the lar and larva: but it is most
probable, that the larvæ, lemures, and dæmones, were all used as
names for what were termed the evil genii.

NOTE 107.

Be to her a friend, a guardian, a parent.


Amicum, tutorem patrem. The word tutorem in this line, alludes
to the Roman custom of appointing guardians, which was usually
performed with great ceremony: frequently on a dead-bed. The
person who intended to constitute a tutor or guardian, made use of
a set form of words, which were spoken before witnesses, when the
ward was delivered to the guardian, with these words, “Hunc (vel
hanc) tibi commendo, Tutor esto.” I commend him (or her) to your
protection, be to him a guardian. Thus Ovid,

“Hæc progeniesque mea est


Hanc tibi commendo.”
Trist., B. III. El. 14. L. 14.

To your protection I commit my offspring.

Some words were also addressed to the ward, as “Hunc tibi


tutorem do,” I appoint this person your guardian.
Donatus observes, that the line
——“Te isti virum do, amicum, tutorem, patrem,”
ought to be read with a long pause between each word, as Terence
intended to describe the broken, interrupted voice of a person at the
point of death.

NOTE 108.

Charinus, Byrrhia.
“These two characters were not in the works of Menander, but
were added to the fable by Terence, lest Philumena’s being left
without a husband, on the marriage of Pamphilus to Glycerium
should appear too tragical a circumstance.—Donatus.
Madame Dacier, after transcribing this remark adds, that it
appears to her to be an observation of great importance to the
theatre, and well worthy our attention.
Important as this dramatic arcanum may be, it were to be
wished, that Terence had never found it out, or, at least, that he had
not availed himself of it in the construction of the Andrian. It is plain
that the duplicity of the intrigue did not proceed from the imitation
of Menander, since these characters, on which the double plot is
founded, were not drawn from the Greek poet. Charinus and Byrrhia
are indeed but poor counterparts, or faint shadows of Pamphilus and
Davus; and, instead of adding life and vigour to the fable, rather
damp its spirit, and stop the activity of its progress. As to the tragical
circumstance of Philumena’s having no husband, it seems something
like the distress of Prince Prettyman[A], who thinks it a matter of
indifference, whether he shall appear to be the son of a king or a
fisherman, and is only uneasy lest he should be the son of nobody at
all. I am much more inclined to the opinion of an ingenious French
critic, whom I have already cited more than once, than to that of
Donatus or Madame Dacier. His comment in this underplot is as
follows:—
“It is almost impossible to conduct two intrigues at a time
without weakening the interest of both. With what address
has Terence interwoven the amours of Pamphilus and
Charinus in the Andrian! But has he done it without
inconvenience? At the beginning of the second act, do we not
seem to be entering upon a new piece? and does the fifth
conclude in a very interesting manner?”—Diderot.
It is but justice to Sir Richard Steele to confess, that he has
conducted the under-plot in the Conscious Lovers in a much more
artful and interesting manner than Terence in the play before us.
The part which Myrtle sustains (though not wholly unexceptionable,
especially the last act,) is more essential to the fable than Charinus
in the Andrian. His character also is more separated and
distinguished from Bevil, than Charinus from Pamphilus, and serves
to produce one of the best scenes[B] in the play.” Colman.

[A] The following extract will explain Mr. Colman’s allusion,


Thimble. Brave Prettyman, it is at length revealed,
That he is not thy Sire who thee conceal’d.
Prettyman. What oracle this darkness can evince!
Sometimes a fisher’s son, sometimes a prince.
It is a secret, great as is the world;
In which I, like the soul, am toss’d and hurl’d.
The blackest ink of fate sure was my lot,
And when she writ my name, she made a blot.
[Exit.
Bayes. There’s a blustering verse for you now.
Smith. Yes, Sir; but why is he so mightily troubled to
find he is not a fisherman’s son?
Bayes. Phoo! that is not because he has a mind to be
his son, but for fear he should be thought to
be nobody’s son at all.
Smith. Nay, that would trouble a man, indeed.
Rehearsal, A. III. S. IV.
[B] A. IV. S. I.

NOTE 109.

Byrrhia.—I beseech you, O Charinus.


Quæso ædepol, Charine. Ædepol means literally by the temple of
Pollux, being an abbreviation of the words per templum Pollucis, as
pol was used for per Pollucem: and hercle for per Herculem. These
ancient expletives are of a similar nature to those in modern use,
which are almost all of religious derivation.
To affirm a thing by the temple of Pollux, was a very common
expression among the ancients; and is frequently used in the plays
of Terence, where it seems to have been particularly the oath of
slaves. It was natural enough that Athenian slaves should asseverate
by this temple, as it was the place where they were bought and sold
by the inhabitants of Attica. This splendid building, which was so
unworthily employed, was situated in the κάτω πόλις, or the lower
city, towards the sea; and was called Ἀνάκειον, because Castor and
Pollux were called ἄνακες. In the Greek mythology, Castor and Pollux
were the twin sons of Leda: their father, Jupiter, rewarded their
virtues, by giving them a place in the heavens, where they are called
Gemini. They were supposed to preside over martial exercises, (for
their skill in which they were particularly eminent,) and they had the
power of allaying storms. These fables have caused the names of
Castor and Pollux to be given to that well-known meteor which
sometimes appears at sea in the shape of several fire-balls, which
seem to adhere to the vessel, and which are judged to indicate an
approaching calm. This phænomenon is called by the French,
Spaniards, and Italians, San Elmo, or Hermo.

NOTE 110.
Byrrhia.—I beseech you, O Charinus, to wish for something possible,
since what you now wish for is impossible!
Terence always admirably preserves the characters of domestics,
in the style of the advice they give their masters, which is very often
conveyed in some trite adage, or formal apothegm. This is another
instance of our author’s art. Want of attention to the dialogue of the
inferior characters, is a frequent fault among dramatic writers; and
often proves hostile to the success of a piece, particularly of a
comedy, where it is absolutely essential.

NOTE 111.

To nourish a hopeless passion.


Madame Dacier observes, with her usual judgment, that Terence
simplifies a philosophical maxim in so elegant and familiar a manner,
that it assumes a grace, even from the lips of a domestic. Diderot
makes a similar remark in the Preface to his Père de Famille; which
he probably remembered from the learned lady before mentioned.
Montaigne has elegantly expressed the sense of Byrrhia’s speech.
C’est foiblesse de ceder aux maux, mais c’est folie de les nourrir.
NOTE 112.
Charinus.—What think you, Byrrhia, shall I speak to him?
Byrrhia.—Why not? that even if you can obtain nothing, you may
make him think, at least, that Philumena will find a pressing
gallant in you, if he marries her.
The original of these lines is the most exceptionable passage in
this play.

“C. Byrrhia,
Quid tibi videtur? Adeon’ ad eum? B. Quidni? si nihil impetres,
Ut te arbitretur sibi paratum mœchum, si illam duxerit.”

The ingenious French editor, mentioned in Note 72, has given the
following elegant and delicate turn to this objectionable passage.

“C. Byrrhia,
Quid tibi videtur? Adeon’ ad eum? B. Quidni? ut, si nihil impetres,
Te sibi cavendum credat, si illam duxerit.”

NOTE 113.

You see me to-day for the last time.


Though Charinus means, that the misery of losing Philumena
would cost him his life, as he expressly tells Davus in the next scene,
yet he only insinuates this by saying, You will never see me again:
and avoids the mention of death: which was considered among the
Greeks as a word that should scarcely ever be named: and it was
reckoned the height of ill breeding to discourse in company
respecting human mortality; which was a subject to be spoken of
only by distant hints: (vide Note 190.) This whole scene is admirably
written; and as well as the last scene in the first act, is a specimen
of Terence’s powers in the pathetic. Some very ingenious remarks on
this scene are to be found in Donatus, and in the Miscellanies of
Nonnius.

NOTE 114.
Now, if either you, or Byrrhia here, can do any thing; in Heavens
name, do it; contrive, invent, and manage, if you can, that she
may be given to you.
It does not appear that Charinus and Byrrhia set any stratagem
on foot, in compliance with the wishes of Pamphilus, to break off the
treaty between Simo and Chremes; indeed, they are rather inactive
throughout the play, and the under-plot proceeds separately from
the principal plot: this, I attribute to Terence’s close imitation of
Menander, in what respects Pamphilus’s intrigue, as the characters of
Charinus and Byrrhia were added by Terence: Menander’s play being
written with a single plot; which was doubled by our author, in
compliance with the taste of his age. It is supposed that Terence’s
reputation for art was gained chiefly by his success in combining two
intrigues in one play: a mode of dramatic writing which the Romans
in those times considered a great novelty. The Stepmother is the
only play written by Terence, in which the plot is single, and though
critics in general argue with Volcatius,
“Sumetur Hecyra sexta ex his fabula,”
that it is not equal to the rest of his productions, many persons, very
eminent for their judgment, have attributed the superiority of the
other five plays, to the advantages they possess over the
Stepmother, both in portraiture of character, and in the conduct of
the catastrophe, and of the fable in general, rather than to any
additional attraction which they can derive from a double plot. The
Carin and Byrrhie of M. Baron, are, in every respect, the
counterparts of the Charinus and Byrrhia of Terence; but Sir R.
Steele has very much enlivened the character of Charinus; his Myrtle
is one of the most entertaining personages in the piece. Vide Notes
108, 159, 162, 163.

NOTE 115.

I know your affair also.


From Byrrhia, whom he had just parted from, as he afterwards
relates: this, though a trivial circumstance, shews Terence’s great
art. Donatus reads this sentence,
“Et tu quid timeas scio.”
but the measure of the verse does not seem to admit of timeas.

NOTE 116.

Not a soul do I see before the door.


The marriage ceremonies of the Greeks were, in many respects,
very similar to those of the Romans. In Athens, as at Rome,
sacrifices were deemed necessary preliminaries to the celebration of
a marriage: and the bride, accompanied by bride-women, whom the
Latins called pronubæ, the Greeks νυμφεύτριαι, was conducted to
her husband’s house with great ceremony; if the parties were of
rank, the bride’s train was increased by the attendance of many of
her friends and relatives, who previously assembled at her father’s
house. It is to the absence of the bride’s train, and of the musicians
who usually assembled before her door, and attended her to her new
habitation, that Davus alludes, when he says, that he could perceive
no company in the house, or before the door. For further information
respecting the marriages of the Greeks and Romans, vide Notes 70,
75, 76, 117, 118, 148, 149, 181.

NOTE 117.
Every thing is quite still and quiet.

You might also like