100% found this document useful (3 votes)
98 views

Complete Download Interactive Data Visualization for the Web 1st Edition Scott Murray PDF All Chapters

Interactive

Uploaded by

elvingkedju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
98 views

Complete Download Interactive Data Visualization for the Web 1st Edition Scott Murray PDF All Chapters

Interactive

Uploaded by

elvingkedju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Visit https://ebookgate.

com to download the full version and


explore more ebooks

Interactive Data Visualization for the Web 1st


Edition Scott Murray

_____ Click the link below to download _____


https://ebookgate.com/product/interactive-data-
visualization-for-the-web-1st-edition-scott-murray/

Explore and download more ebooks at ebookgate.com


Here are some recommended products that might interest you.
You can download now and explore!

Learning IPython for Interactive Computing and Data


Visualization 2nd Edition Cyrille Rossant

https://ebookgate.com/product/learning-ipython-for-interactive-
computing-and-data-visualization-2nd-edition-cyrille-rossant/

ebookgate.com

Data Visualization with Flash Builder Designing RIA and


AIR Applications with Remote Data Sources Visualizing the
Web Cesare Rocchi
https://ebookgate.com/product/data-visualization-with-flash-builder-
designing-ria-and-air-applications-with-remote-data-sources-
visualizing-the-web-cesare-rocchi/
ebookgate.com

Everyday Data Visualization Desiree Abbott

https://ebookgate.com/product/everyday-data-visualization-desiree-
abbott/

ebookgate.com

Learning Qlikview Data Visualization 1st Edition Karl


Pover

https://ebookgate.com/product/learning-qlikview-data-
visualization-1st-edition-karl-pover/

ebookgate.com
Web Cartography Map Design for Interactive and Mobile
Devices 1st Edition Ian Muehlenhaus (Author)

https://ebookgate.com/product/web-cartography-map-design-for-
interactive-and-mobile-devices-1st-edition-ian-muehlenhaus-author/

ebookgate.com

Handbook of Statistics 24 Data Mining and Data


Visualization C.R. Rao

https://ebookgate.com/product/handbook-of-statistics-24-data-mining-
and-data-visualization-c-r-rao/

ebookgate.com

Social Data Visualization with HTML5 and JavaScript Timms

https://ebookgate.com/product/social-data-visualization-with-
html5-and-javascript-timms/

ebookgate.com

HTML5 Graphing and Data Visualization Cookbook 1st Edition


Ben Fhala

https://ebookgate.com/product/html5-graphing-and-data-visualization-
cookbook-1st-edition-ben-fhala/

ebookgate.com

HTML5 graphing and data visualization cookbook learn how


to create interactive HTML5 charts and graphs with canvas
JavaScript and open source tools Ben Fhala
https://ebookgate.com/product/html5-graphing-and-data-visualization-
cookbook-learn-how-to-create-interactive-html5-charts-and-graphs-with-
canvas-javascript-and-open-source-tools-ben-fhala/
ebookgate.com
Interactive Data Visualization
for the Web
Download from Wow! eBook <www.wowebook.com>

Scott Murray
Interactive Data Visualization for the Web
by Scott Murray
Copyright © 2013 Scott Murray. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editor: Meghan Blanchette Indexer: Judith McConville
Production Editor: Melanie Yarbrough Cover Designer: Karen Montgomery
Copyeditor: Teresa Horton Interior Designer: David Futato
Proofreader: Linley Dolby Illustrator: Rebecca Demarest

March 2013: First Edition

Revision History for the First Edition:


2013-03-04: First release

2013-04-12: Second release

See http://oreilly.com/catalog/errata.csp?isbn=9781449339739 for release details.

Nutshell Handbook, the Nutshell Handbook logo, the cover image, and the O’Reilly logo are registered
trademarks of O’Reilly Media, Inc. Interactive Data Visualization for the Web, the cover image of a long-tail
bushtit, and related trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐
mark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.

ISBN: 978-1-449-33973-9
[LSI]
Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

1. Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Why Data Visualization? 1
Why Write Code? 2
Why Interactive? 2
Why on the Web? 3
What This Book Is 3
Who You Are 4
What This Book Is Not 5
Using Sample Code 5
Thank You 6

2. Introducing D3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
What It Does 7
What It Doesn’t Do 8
Origins and Context 9
Alternatives 10
Easy Charts 10
Graph Visualizations 12
Geomapping 12
Almost from Scratch 13
Three-Dimensional 13
Tools Built with D3 14

3. Technology Fundamentals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
The Web 15
HTML 17
Content Plus Structure 18

iii
Adding Structure with Elements 19
Common Elements 20
Attributes 22
Classes and IDs 22
Comments 23
DOM 24
Developer Tools 24
Rendering and the Box Model 27
CSS 29
Selectors 29
Properties and Values 31
Comments 31
Referencing Styles 31
Inheritance, Cascading, and Specificity 33
JavaScript 35
Hello, Console 35
Variables 35
Other Variable Types 36
Arrays 36
Objects 37
Objects and Arrays 38
Mathematical Operators 40
Comparison Operators 41
Control Structures 41
Functions 43
Comments 44
Referencing Scripts 44
JavaScript Gotchas 45
SVG 49
The SVG Element 50
Simple Shapes 50
Styling SVG Elements 53
Layering and Drawing Order 54
Transparency 55
A Note on Compatibility 57

4. Setup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Downloading D3 59
Referencing D3 60
Setting Up a Web Server 61
Terminal with Python 61
MAMP, WAMP, and LAMP 62

iv | Table of Contents
Diving In 62

5. Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Generating Page Elements 63
Chaining Methods 65
One Link at a Time 66
The Hand-off 67
Going Chainless 67
Binding Data 67
In a Bind 67
Data 68
Please Make Your Selection 72
Bound and Determined 73
Using Your Data 76
High-Functioning 77
Data Wants to Be Held 78
Beyond Text 79

6. Drawing with Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81


Drawing divs 81
Setting Attributes 82
A Note on Classes 83
Back to the Bars 83
Setting Styles 84
The Power of data() 85
Random Data 87
Drawing SVGs 89
Create the SVG 89
Data-Driven Shapes 90
Pretty Colors, Oooh! 92
Making a Bar Chart 92
The Old Chart 93
The New Chart 93
Color 98
Labels 101
Making a Scatterplot 103
The Data 103
The Scatterplot 104
Size 105
Labels 106

Table of Contents | v
Next Steps 107

7. Scales. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Apples and Pixels 109
Domains and Ranges 110
Normalization 111
Creating a Scale 111
Scaling the Scatterplot 112
d3.min() and d3.max() 112
Setting Up Dynamic Scales 114
Incorporating Scaled Values 114
Refining the Plot 115
Other Methods 119
Other Scales 119

8. Axes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Introducing Axes 121
Setting Up an Axis 122
Cleaning It Up 123
Check for Ticks 126
Y Not? 127
Final Touches 128
Formatting Tick Labels 130

9. Updates, Transitions, and Motion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133


Modernizing the Bar Chart 133
Ordinal Scales, Explained 134
Round Bands Are All the Range These Days 136
Referencing the Ordinal Scale 136
Other Updates 137
Updating Data 137
Interaction via Event Listeners 138
Changing the Data 139
Updating the Visuals 139
Transitions 142
duration(), or How Long Is This Going to Take? 143
ease()-y Does It 144
Please Do Not delay() 145
Randomizing the Data 147
Updating Scales 150
Updating Axes 152
each() Transition Starts and Ends 153

vi | Table of Contents
Other Kinds of Data Updates 161
Adding Values (and Elements) 161
Removing Values (and Elements) 166
Data Joins with Keys 169
Add and Remove: Combo Platter 174
Recap 176

10. Interactivity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177


Binding Event Listeners 177
Introducing Behaviors 178
Hover to Highlight 179
Grouping SVG Elements 184
Click to Sort 185
Tooltips 188
Default Browser Tooltips 189
SVG Element Tooltips 190
HTML div Tooltips 192
Consideration for Touch Devices 195
Moving Forward 195

11. Layouts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197


Pie Layout 198
Stack Layout 202
Force Layout 206

12. Geomapping. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213


JSON, Meet GeoJSON 213
Paths 215
Projections 216
Choropleth 219
Adding Points 222
Acquiring and Parsing Geodata 226
Find Shapefiles 226
Choose a Resolution 226
Simplify the Shapes 228
Convert to GeoJSON 228

13. Exporting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233


Bitmaps 233
PDF 234

Table of Contents | vii


SVG 235

A. Appendix: Further Study. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Download from Wow! eBook <www.wowebook.com>

viii | Table of Contents


Preface

This is a book about programming data visualizations for nonprogrammers. If you’re


an artist or graphic designer with visual skills but no prior experience working with data
or code, this book is for you. If you’re a journalist or researcher with lots of data but no
prior experience working with visuals or code, this book is for you, too.
This book will introduce you to D3, a JavaScript-based tool for loading data into a web
page and generating visuals from that data. I assume that you have little or no pro‐
gramming experience. Or, perhaps you have programmed before, but D3 and data vis‐
ualization are bringing you to JavaScript for the first time, and you’ve heard bad things
about it. Well, JavaScript is a little weird, but it’s not as bad as you’ve heard, and every‐
thing is going to be all right. Please sit down and make yourself comfortable.
This book began as a series of tutorials posted on my website. At the time (January 2012),
there wasn’t much information on D3 available that was accessible to beginners. Very
quickly, I was getting hundreds, then thousands of page views a day—evidence that
interest in the field generally (and D3 specifically) was growing like gangbusters. If
you’ve read the tutorials, portions of the book will feel familiar, but there is a lot of new
material here, including many more examples, sneaky tips, and warnings of things to
avoid. Also, the book contains 78 percent more bad jokes.
Data visualization is an interdisciplinary field, which is just one reason it’s impossible
to document the breadth of skills needed in a single book. Fortunately, because the field
is exploding in popularity, there are many new titles to choose from, each of which
complements this one.
On design process:

• Designing Data Visualizations: Intentional Communication from Data to Display


by Noah Iliinsky and Julie Steele. O’Reilly Media, 2011.
• Data Visualization: A Successful Design Process by Andy Kirk. Packt Publishing,
2012.

ix
On visual design principles and techniques:

• The Functional Art: An Introduction to Information Graphics and Visualization by


Alberto Cairo. New Riders, 2012.
• Information Dashboard Design: The Effective Visual Communication of Data by
Stephen Few. O’Reilly Media, 2006.

On the practicalities of working with data:

• Bad Data Handbook: Mapping the World of Data Problems by Q. Ethan McCallum.
O’Reilly Media, 2012.
• Data Analysis with Open Source Tools: A Hands-On Guide for Programmers and
Data Scientists by Philipp K. Janert. O’Reilly Media, 2010.
• Python for Data Analysis: Agile Tools for Real World Data by Wes McKinney.
O’Reilly Media, 2012.

Conventions Used in This Book


The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program elements
such as variable or function names, databases, data types, environment variables,
statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.

This icon signifies a tip, suggestion, or general note.

This icon indicates a warning or caution.

x | Preface
Using Code Examples
This book is here to help you get your job done. In general, if this book includes code
examples, you may use the code in this book in your programs and documentation. You
do not need to contact us for permission unless you’re reproducing a significant portion
of the code. For example, writing a program that uses several chunks of code from this
book does not require permission. Selling or distributing a CD-ROM of examples from
O’Reilly books does require permission. Answering a question by citing this book and
quoting example code does not require permission. Incorporating a significant amount
of example code from this book into your product’s documentation does require per‐
mission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: “Interactive Data Visualization for the Web
by Scott Murray (O’Reilly). Copyright 2013 Scott Murray, 978-1-449-33973-9.”
If you feel your use of code examples falls outside fair use or the permission given above,
feel free to contact us at permissions@oreilly.com.

Safari® Books Online


Safari Books Online is an on-demand digital library that delivers ex‐
pert content in both book and video form from the world’s leading
authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research, prob‐
lem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi‐
zations, government agencies, and individuals. Subscribers have access to thousands of
books, training videos, and prepublication manuscripts in one fully searchable database
from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐
fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John
Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT
Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐
ogy, and dozens more. For more information about Safari Books Online, please visit us
online.

Preface | xi
How to Contact Us
Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.


1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://oreil.ly/interactive_data_visualiza
tion_web.
To comment or ask technical questions about this book, send email to bookques
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments
My name may be on the cover, but as an author, I feel as though I am merely funneling
the wisdom of hundreds of other brilliant minds onto the page.
First and foremost, I must thank my wife Nora, not least for being the first to say “Hey,
you should turn those tutorials into a book.” Without her support and encouragement,
this project never would have happened.
Thanks also to Rosten Woo, with whom I collaborated on my first D3 project, for
reaching out and giving me a reason to finally dig into this new tool. Thanks to Joe
Golike for several early D3 debugging sessions around that time, and to Jen Lowe and
Sha Hwang for their reviews and feedback on the initial tutorials.
I am extremely grateful to Casey Reas, Dan Shiffman, Joshua Noble, and Noah Iliinsky
—not just for offering advice on the book-creation process, but also for their ground‐
breaking work in the spheres of art, design, code, and data. Their careers have greatly
influenced my own.

xii | Preface
In that vein, I should also thank Jan Kubasiewicz at MassArt’s Dynamic Media Insti‐
tute. Back in 2007, Jan encouraged me to check out something called Processing, which
eventually led me to a whole new career in code-driven arts, data visualization, and now
this book.
It has been a pleasure working with my editor, Meghan Blanchette, and everyone else
on the team at O’Reilly. Thanks to Meghan and her crew for shepherding this project
all the way through, from concept to an actual, physical, chunk of paper with words and
strange diagrams printed on it.
Special thanks to Mike Bostock, Jen Lowe, Anna Powell-Smith, and Daisy Vincent for
agreeing to tech review the book and sending incredibly valuable feedback. The final
product is vastly improved, thanks to their input. That said, if you find an error or
confusing code example, it is because they begged me to rewrite it, and I steadfastly
refused.
Mike gets an extra-special thanks for developing D3 in the first place. Without this
elegant piece of software, the community of data visualization practitioners wouldn’t be
quite as vibrant, enthusiastic, and standards-compliant as it is today.
Speaking of community, many other people—including Jérôme Cukier, Lynn Cherny,
Jason Davies, Jeff Heer, Santiago Ortiz, Kim Rees, Moritz Stefaner, Jan Willem Tulp,
and others who I have forgotten to mention—on the D3 list and in nearby orbits have
also directly contributed to my thinking and process. Thank you for your support. I am
lucky to get to collaborate with so many talented people.

Preface | xiii
CHAPTER 1
Introduction

Why Data Visualization?


Our information age more often feels like an era of information overload. Excess
amounts of information are overwhelming; raw data becomes useful only when we apply
methods of deriving insight from it.
Fortunately, we humans are intensely visual creatures. Few of us can detect patterns
among rows of numbers, but even young children can interpret bar charts, extracting
meaning from those numbers’ visual representations. For that reason, data visualization
is a powerful exercise. Visualizing data is the fastest way to communicate it to others.
Of course, visualizations, like words, can be used to lie, mislead, or distort the truth. But
when practiced honestly and with care, the process of visualization can help us see the
world in a new way, revealing unexpected patterns and trends in the otherwise hidden
information around us. At its best, data visualization is expert storytelling.
More literally, visualization is a process of mapping information to visuals. We craft
rules that interpret data and express its values as visual properties. For example, the
humble bar chart in Figure 1-1 is generated from a very simple rule: larger values are
mapped as taller bars.

Figure 1-1. Data values mapped to visuals

1
More complex visualizations are generated from datasets more complex than the se‐
quence of numbers shown in Figure 1-1 and more complex sets of mapping rules.

Why Write Code?


Mapping data by hand can be satisfying, yet is slow and tedious. So we usually employ
the power of computation to speed things up. The increased speed enables us to work
with much larger datasets of thousands or millions of values; what would have taken
years of effort by hand can be mapped in a moment. Just as important, we can rapidly
experiment with alternate mappings, tweaking our rules and seeing their output re-
rendered immediately. This loop of write/render/evaluate is critical to the iterative pro‐
cess of refining a design.
Sets of mapping rules function as design systems. The human hand no longer executes
the visual output; the computer does. Our human role is to conceptualize, craft, and
write out the rules of the system, which is then finally executed by software.
Unfortunately, software (and computation generally) is extremely bad at understanding
what, exactly, people want. (To be fair, many humans are also not good at this challenging
task.) Because computers are binary systems, everything is either on or off, yes or no,
this or that, there or not there. Humans are mushier, softer creatures, and the computers
are not willing to meet us halfway—we must go to them. Hence the inevitable struggle
of learning to write software, in which we train ourselves to communicate in the very
limited and precise syntax that the computer can understand.
Yet we continue to write code because seeing our visual creations come to life is so
rewarding. We practice data visualization because it is exciting to see what has never
before been seen. It is like summoning a magical, visual genie out of an inscrutable data
bottle.

Why Interactive?
Static visualizations can offer only precomposed “views” of data, so multiple static views
are often needed to present a variety of perspectives on the same information. The
number of dimensions of data are limited, too, when all visual elements must be present
on the same surface at the same time. Representing multidimensional datasets fairly in
static images is notoriously difficult. A fixed image is ideal when alternate views are
neither needed nor desired, and required when publishing to a static medium, such as
print.
Dynamic, interactive visualizations can empower people to explore the data for them‐
selves. The basic functions of most interactive visualization tools have changed little
since 1996, when Ben Shneiderman of the University of Maryland first proposed a

2 | Chapter 1: Introduction
“Visual Information-Seeking Mantra”: overview first, zoom and filter, then details-on-
demand.
This design pattern is found in most interactive visualizations today. The combination
of functions is successful, because it makes the data accessible to different audiences,
from those who are merely browsing or exploring the dataset to those who approach
the visualization with a specific question in search of an answer. An interactive visual‐
ization that offers an overview of the data alongside tools for “drilling down” into the
details may successfully fulfill many roles at once, addressing the different concerns of
different audiences, from those new to the subject matter to those already deeply familiar
with the data.
Of course, interactivity can also encourage engagement with the data in ways that static
images cannot. With animated transitions and well-crafted interfaces, some visualiza‐
tions can make exploring data feel more like playing a game. Interactive visualization
can be a great medium for engaging an audience who might not otherwise care about
the topic or data at hand.

Why on the Web?


Visualizations aren’t truly visual unless they are seen. Getting your work out there for
others to see is critical, and publishing on the Web is the quickest way to reach a global
audience. Working with web-standard technologies means that your work can be seen
and experienced by anyone using a recent web browser, regardless of the operating
system (Windows, Mac, Linux) and device type (laptop, desktop, smartphone, tablet).
Best of all, everything covered in this book can be done with freely accessible tools, so
the only investment required is your time. And everything we’ll talk about uses open
source, web-standard technologies.
By avoiding proprietary software and plug-ins, you can ensure that your projects are
accessible on the widest possible range of devices, from typical desktop computers to
tablets and even phones. The more accessible your visualization, the greater your au‐
dience and your impact.

What This Book Is


This book is a practical introduction to merging three practices—data visualization,
interactive design, and web development—using D3, a powerful tool for custom, web-
based visualization.
These chapters grew out of my own process of learning how to use D3. Many people,
including myself, come to D3 with backgrounds in design, mapping, and data visuali‐
zation, but not programming and computer science.

Why on the Web? | 3


D3 has a bit of an unfair reputation for being hard to learn. D3 itself is not so complicated,
but it operates in the domain of the Web, and the Web is complicated. Using D3 com‐
fortably requires some prior knowledge of the web technologies with which it interacts,
such as HTML, CSS, JavaScript, and SVG. Many people (myself included) are self-taught
when it comes to web skills. This is great, because the barrier to entry is so low, but
problematic because it means we probably didn’t learn each of these technologies from
the ground up—more often, we just hack something together until it seems to work,
and call it a day. Yet successful use of D3 requires understanding some of these tech‐
nologies in a fundamental way.
Because D3 is written in JavaScript, learning to use D3 often means learning a lot about
JavaScript. For many datavis folks, D3 is their introduction to JavaScript (or even web
development generally). It’s hard enough to learn a new programming language, let
alone a new tool built on that language. D3 will enable you to do great things with
JavaScript that you never would have even attempted. The time you spend learning both
the language and the tool will provide an incredible payoff.
My goal is to reduce that learning time, so you can start creating awesome stuff sooner.
We’ll take a ground-up approach, starting with the fundamental concepts and gradually
adding complexity. I don’t intend to show you how to make specific kinds of visualiza‐
tions so much as to help you understand the workings of D3 well enough to take those
building blocks and generate designs of your own creation.

Who You Are


You may be an absolute beginner, someone new to datavis, web development, or both.
(Welcome!) Perhaps you are a journalist interested in new ways to communicate the
data you collect during reporting. Or maybe you’re a designer, comfortable drawing
static infographics but ready to make the leap to interactive projects on the Web. You
could be an artist, interested in generative, data-based art. Or a programmer, already
familiar with JavaScript and the Web, but excited to learn a new tool and pick up some
visual design experience along the way.
Whoever you are, I hope that you:

• Have heard of this new thing called the “World Wide Web”
• Are a bit familiar with HTML, the DOM, and CSS
• Might even have a little programming experience already
• Have heard of jQuery or written some JavaScript before
• Aren’t scared by unknown initialisms like CSV, SVG, or JSON
• Want to make useful, interactive visualizations

4 | Chapter 1: Introduction
If any of those things are unknown or unclear, don’t fear. You might just want to spend
more time with Chapter 3, which covers what you really need to know before diving
into D3.

What This Book Is Not


That said, this is definitely not a computer science textbook, and it is not intended to
teach the intricacies of any one web technology (HTML, CSS, JavaScript, SVG) in depth.
In that spirit, I might gloss over some technical points, grossly oversimplifying impor‐
tant concepts fundamental to computer science in ways that will make true software
engineers recoil. That’s fine, because I’m writing for artists and designers here, not en‐
gineers. We’ll cover the basics, and then you can dive into the more complex pieces once
you’re comfortable.
Download from Wow! eBook <www.wowebook.com>

I will deliberately not address every possible approach to a given problem, but will
typically present what I feel is the simplest solution, or, if not the simplest, then the most
understandable.
My goal is to teach you the fundamental concepts and methods of D3. As such, this
book is decidedly not organized around specific example projects. Everyone’s data and
design needs will be different. It’s up to you to integrate these concepts in the way best
suited to your particular project.

Using Sample Code


If you are a mad genius, then you can probably learn to use D3 without ever looking at
any sample code files, in which case you can skip the rest of this section.
If you’re still with me, you are probably still very bright but not mad, in which case you
should undertake this book with the full set of accompanying code samples in hand.
Before you go any further, please download the sample files from GitHub.
Normal people will want to click the ZIP link to download a compressed ZIP archive
with all the files. Hardcore geeksters will want to clone the repository using Git. If that
last sentence sounds like total gibberish, please use the first option.
Within the download, you’ll notice there is a folder for each chapter that has code to go
with it:
chapter_04
chapter_05
chapter_06
chapter_07
chapter_08

What This Book Is Not | 5


Files are organized by chapter, so in Chapter 9 when I reference 01_bar_chart.html,
know that you can find that file in the corresponding location: d3-book/chap‐
ter_9/01_bar_chart.html.
You are welcome to copy, adapt, modify, and reuse the example code in these tutorials
for any noncommercial purpose.

Thank You
Finally, this book has been handcrafted, carefully written, and pedagogically fine-tuned
for maximum effect. Thank you for reading it. I hope you learn a great deal, and even
have some fun along the way.

6 | Chapter 1: Introduction
CHAPTER 2
Introducing D3

D3—also referred to as D3 or d3.js—is a JavaScript library for creating data visualiza‐


tions. But that kind of undersells it.
The abbreviation D3 references the tool’s full name, Data-Driven Documents. The da‐
ta is provided by you, and the documents are web-based documents, meaning anything
that can be rendered by a web browser, such as HTML and SVG. D3 does the driving,
in the sense that it connects the data to the documents.
Of course, the name also functions as a clever allusion to the network of technologies
underlying the tool itself: the W3, or World Wide Web, or, today, simply “the Web.”
D3’s primary author is the brilliant Mike Bostock, although there are a few other dedi‐
cated contributors. The project is entirely open source and freely available on GitHub.
D3 is released under a BSD license, so you may use, modify, and adapt the code for
noncommercial or commercial use at no cost.
D3’s official home on the Web is d3js.org.

What It Does
Fundamentally, D3 is an elegant piece of software that facilitates generation and ma‐
nipulation of web documents with data. It does this by:

• Loading data into the browser’s memory


• Binding data to elements within the document, creating new elements as needed

7
• Transforming those elements by interpreting each element’s bound datum and set‐
ting its visual properties accordingly
• Transitioning elements between states in response to user input

Learning to use D3 is simply a process of learning the syntax used to tell it how you
want it to load and bind data, and transform and transition elements.
The transformation step is most important, as this is where the mapping happens. D3
provides a structure for applying these transformations, but, as we’ll see, you define the
mapping rules. Should larger values make taller bars or brighter circles? Will clusters
be sorted on the x-axis by age or category? What color palette is used to fill in countries
on your world map? All of the visual design decisions are up to you. You provide the
concept, you craft the rules, and D3 executes it—without telling you what to do. (Yes,
it’s like the opposite of Excel’s pushy “Chart Wizard.”)

What It Doesn’t Do
Here is a list of things D3 does not do:

• D3 doesn’t generate predefined or “canned” visualizations for you. This is on pur‐


pose. D3 is intended primarily for explanatory visualization work, as opposed to
exploratory visualizations. Exploratory tools help you discover significant, mean‐
ingful patterns in data. These are tools like Tableau and ggplot2, which help you
quickly generate multiple views on the same data set. That’s an essential step, but
different from generating an explanatory presentation of the data, a view of the data
that highlights what you’ve already discovered. Explanatory views are more con‐
strained and limited, but also focused, and designed to communicate only the im‐
portant points. D3 excels at this latter step, but is not ideal for the former. (For ideas
on other tools, see the section “Alternatives” on page 10 later in this chapter.)
• D3 doesn’t even try to support older browsers. This helps keep the D3 codebase
clean and free of hacks to support old versions of Internet Explorer, for example.
The philosophy is that by creating more compelling tools and refusing to support
older browsers, we encourage more people to upgrade (rather than forestall the
process, thereby requiring us to continue to support those browsers, and so on—a
vicious cycle). D3 wants us to move forward.
• D3’s core functionality doesn’t handle bitmap map tiles, such as those provided by
Google Maps or Cloudmade. D3 is great with anything vector—SVG images or
GeoJSON data—but wasn’t originally intended to work with traditional map tiles.
(Bitmap images are made up of pixels, so resizing them larger or smaller is difficult
without a loss in quality. Vector images are defined by points, lines, and curves—
mathematical equations, really—and can be scaled up or down without a loss in
quality.) This is starting to change, with the introduction of the d3.geo.tile plug-

8 | Chapter 2: Introducing D3
in. Prior to this plug-in, geomapping with D3 meant either going all-SVG and
avoiding tiles or using D3 to create SVG visuals on top of a base layer of map tiles
(which would be managed by another library, like Leaflet or Polymaps—see the
section “Alternatives” on page 10 later in this chapter). This question of how to in‐
tegrate bitmap tiles and vector graphics comes up a lot in the D3 community. As of
today, there is no super-simple and perfect answer, but I think you can expect to
see lots of work done in this area, and possibly the new tile-handling methods
integrated into the D3 core at some point in the future.
• D3 doesn’t hide your original data. Because D3 code is executed on the client side
(meaning, in the user’s web browser, as opposed to on the web server), the data you
want visualized must be sent to the client. If your data can’t be shared, then don’t
use D3. Alternatives include using proprietary tools (like Flash) or prerendering
visualizations as static images and sending those to the browser. (If you’re not in‐
terested in sharing your data, though, why would you bother visualizing it? The
purpose of visualization is to communicate the data, so you might sleep better at
night by choosing openness and transparency, rather than having nightmares about
data thieves.)

Origins and Context


The first web browsers rendered static pages; interactivity was limited to clicking links.
In 1996, Netscape introduced the first browser with JavaScript, a new scripting language
that could be interpreted by the browser while the page was being viewed.
This doesn’t sound as groundbreaking as it turned out to be, but this enabled web
browsers to evolve from merely passive browsers to dynamic frames for interactive,
networked experiences. This shift ultimately enabled every intrapage interaction we
have on the Web today. Without JavaScript, D3 would never exist, and web-based data
visualizations would be limited to prerendered, noninteractive GIFs. (Yuck. Thank you,
Netscape!)
Jump ahead to 2005, when Jeffrey Heer, Stuart Card, and James Landay introduced
prefuse, a toolkit for bringing data visualization to the Web. prefuse (spelled with all
lowercase letters) was written in Java, a compiled language, with programs that could
run in web browsers via a Java plug-in. (Note that Java is a completely different pro‐
gramming language than JavaScript, despite their similar names.)
prefuse was a breakthrough application—the first to make web-based visualization ac‐
cessible to less-than-expert programmers. Until prefuse came along, any datavis on the
Web was very much a custom affair.
Two years later, Jeff Heer introduced Flare, a similar toolkit, but written in ActionScript,
so its visualizations could be viewed on the Web through Adobe’s Flash Player. Flare,

Origins and Context | 9


like prefuse, relied on a browser plug-in. Flare was a huge improvement, but as web
browsers continued to evolve, it was clear that visualizations could be created with native
browser technology, no plug-ins required.
By 2009, Jeff Heer had moved to Stanford, where he was advising a graduate student
named Michael Bostock. Together, in Stanford’s Vis Group, they created Protovis, a
JavaScript-based visualization toolkit that relied exclusively on native browser technol‐
ogies. (If you have used Protovis, be sure to reference Mike’s introduction to D3 for
Protovis users.)
Protovis made generating visualizations simple, even for users without prior program‐
ming experience. Yet to achieve this, it created an abstract representation layer. The
designer could address this layer using Protovis syntax, but it wasn’t accessible through
standard methods, so debugging was difficult.
In 2011, Mike Bostock, Vadim Ogievetsky, and Jeff Heer officially announced D3, the
next evolution in web visualization tools. Unlike Protovis, D3 operates directly on the
web document itself. This means easier debugging, easier experimentation, and more
visual possibilities. The only downside to this approach is a potentially steeper learning
curve, but this book will make that as painless as possible. Plus, all the skills you gain
while learning about D3 will prove useful even beyond the realm of datavis.
If you’re familiar with any of these groundbreaking tools, you’ll appreciate that D3 de‐
scends from a prestigious lineage. And if you have any interest in the philosophy un‐
derlying D3’s elegant technical design, I highly recommend Mike, Vadim, and Jeff ’s
InfoVis paper, which clearly articulates the need for this kind of tool. The paper encap‐
sulates years’ worth of learning and insights made while developing visualization tools.

Alternatives
D3 might not be perfect for every project. Sometimes you just need a quick chart and
you don’t have time to code it from scratch. Or you might need to support older browsers
and can’t rely on recent technologies like SVG.
For those situations, it’s good to know what other tools are out there. Here is a brief,
noncomprehensive list of D3 alternatives, all of which use web-standard technologies
(mostly JavaScript) and are free to download and use.

Easy Charts
DataWrapper
A beautiful web service that lets you upload your data and quickly generate a chart
that you can republish elsewhere or embed on your site. This service was originally
intended for journalists, but it is helpful for everyone. DataWrapper displays in‐

10 | Chapter 2: Introducing D3
teractive charts in current browsers and static images for old ones. (Brilliant!) You
can also download all the code and run it on your own server instead of using theirs.
Flot
A plotting library for jQuery that uses the HTML canvas element and supports
older browsers, even all the way back to Internet Explorer 6. It supports limited
visual forms (lines, points, bars, areas), but it is easy to use.
Google Chart Tools
Having evolved from their earlier Image Charts API, Google’s Chart Tools can be
used to generate several standard chart types, with support for old versions of IE.
gRaphaël
A charting library based on Raphaël (see later in this chapter) that supports older
browsers, including IE6. It has more visual flexibility than Flot, and—some might
say—it is prettier.
Highcharts JS
A JavaScript-based charting library with several predesigned themes and chart
types. It uses SVG for modern browsers and falls back on VML for old versions of
IE, including IE6 and later. The tool is free only for noncommercial use.
JavaScript InfoVis Toolkit
The JIT provides several preset visualization styles for your data. It includes lots of
examples, but the documentation is pretty technical. The toolkit is great if you like
one of the preset styles, but browser support is unclear.
jqPlot
A plug-in for charting with jQuery. This supports very simple charts and is great if
you are okay with the predefined styles. jqPlot supports IE7 and newer.
jQuery Sparklines
A jQuery plug-in for generating sparklines, typically small bar, line, or area charts
used inline with text. Supports most browsers, even back to IE6.
Peity
A jQuery plug-in for very simple and very tiny bar, line, and pie charts that supports
only recent browsers. Did I mention that this makes only very tiny visualizations?
+10 cuteness points.
Timeline.js
A library specifically for generating interactive timelines. No coding is required;
just use the code generator. There is not much room for customization, but hey,
timelines are really hard to do well. Timeline.js supports only IE8 and newer.

Alternatives | 11
YUI Charts
The Charts module for the Yahoo! User Interface Library enables creation of simple
charts with a goal of wide browser support.

Graph Visualizations
A “graph” is just data with a networked structure (for example, B is connected to A, and
A is connected to C).
Arbor.js
A library for graph visualization using jQuery. Even if you never use this, you should
check out how the documentation is presented as a graph, using the tool itself. (It’s
so meta.) It uses the HTML canvas, so it works only in IE9 or current browsers,
although some workarounds are available.
Sigma.js
A very lightweight library for graph visualization. You have to visit this website,
move your mouse over the header graphic, and then play with the demos. Sigma.js
is beautiful and fast, and it also uses canvas.

Geomapping
I distinguish between mapping (all visualizations are maps) and geomapping (visuali‐
zations that include geographic data, or geodata, such as traditional maps). D3 has a lot
of geomapping functionality, but you should know about these other tools.
Kartograph
A JavaScript-and-Python combo for gorgeous, entirely vector-based mapping by
Gregor Aisch with must-see demos. Please go look at them now. I promise you’ve
never seen online maps this beautiful. Kartograph works with IE7 and newer.
Leaflet
A library for tiled maps, designed for smooth interaction on both desktop and
mobile devices. It includes some support for displaying data layers of SVG on top

12 | Chapter 2: Introducing D3
of the map tiles. (See Mike’s demo “Using D3 with Leaflet”.) Leaflet works with IE6
(barely) or IE7 (better!) and of course all current browsers.
Modest Maps
The granddaddy of tiled map libraries, Modest Maps has been succeeded by Poly‐
maps, but lots of people still love it, as it is lightweight and works with old versions
of IE and other browsers. Modest Maps has been adapted for ActionScript, Pro‐
cessing, Python, PHP, Cinder, openFrameworks…yeah, basically everything. File
this under “oldie, but goodie.”
Polymaps
A library for displaying tiled maps, with layers of data on top of the tiles. Polymaps
relies on SVG and thus works best with current browsers.

Almost from Scratch


These tools, like D3, provide methods of drawing visual forms, but without predesigned
visual templates. If you enjoy the creative freedom of starting from scratch, you might
enjoy these.
Processing.js
A native JavaScript implementation of Processing, the fantastic programming lan‐
guage for artists and designers new to programming. Processing is written in Java,
so exporting Processing sketches to the Web traditionally involved clunky Java
applets. Thanks to Processing.js, regular Processing code can run natively, in the
browser. It renders using canvas, so only modern browsers are supported.
Paper.js
A framework for rendering vector graphics to canvas. Also, its website is one of the
most beautiful on the Internet, and their demos are unbelievable. (Go play with
them now.)
Raphaël
Another library for drawing vector graphics, popular due to its friendly syntax and
support for older browsers.

Three-Dimensional
D3 is not the best at 3D, simply because web browsers are historically two-dimensional
beasts. But with increased support for WebGL, there are now more opportunities for
3D web experiences.
PhiloGL
A WebGL framework specifically for 3D visualization.

Alternatives | 13
Three.js
A library for generating any sort of 3D scene you could imagine, produced by
Google’s Data Arts team. You could spend all day exploring the mind-blowing de‐
mos on their site.

Tools Built with D3


When you want to use D3 without actually writing any D3 code, you can choose one of
the many tools built on top of D3!
Crossfilter
A library for working with large, multivariate datasets, written primarily by Mike
Bostock. This is useful for trying to squeeze your “big data” into a relatively small
web browser.
Cubism
A D3 plug-in for visualizing time series data, also written by Mike Bostock. (One
of my favorite demos.)
Dashku
An online tool for data dashboards and widgets updated in real time, by Paul Jensen.
dc.js
The “dc” is short for dimensional charting, as this library is optimized for exploring
large, multidimensional datasets.
NVD3
Reusable charts with D3. NVD3 offers lots of beautiful examples, with room for
visual customizations without requiring as much code as D3 alone.
Polychart.js
More reusable charts, with a range of chart types available. Polychart.js is free only
for noncommercial use.
Rickshaw
A toolkit for displaying time series data that is also very customizable.
Tributary
A great tool for experimenting with live coding using D3, by Ian Johnson.

14 | Chapter 2: Introducing D3
CHAPTER 3
Technology Fundamentals
Download from Wow! eBook <www.wowebook.com>

Solid familiarity with the following concepts will make your time with D3 a lot less
frustrating and a lot more rewarding. Consider this a brief refresher course on Web-
Making 101.

Beware! This is a pretty dense chapter, packed with years’ worth of web
development knowledge, and nothing in here is specific to D3. I rec‐
ommend skimming just the sections on information that is new to you,
and skipping the rest. You can always reference this chapter later as
questions arise.

The Web
If you’re brand new to making web pages, you will now have to think about things that
regular people blissfully disregard every day, such as this: How does the Web actually
work?
We think of the Web as a bunch of interlinked pages, but it’s really a collection of con‐
versations between web servers and web clients (browsers).
The following scene is a dramatization of a typical such conversation that happens
whenever you or anyone else clicks a link or types an address into your browser (mean‐
ing, this brief conversation is had about 88 zillion times every day):

CLIENT: I’d really like to know what’s going on over at somewebsite.com. I better call over
there to get the latest info. [Silent sound of Internet connection being established.]
SERVER: Hello, unknown web client! I am the server hosting somewebsite.com. What
page would you like?
CLIENT: This morning, I am interested in the page at somewebsite.com/news/.
SERVER: Of course, one moment.

15
Code is transmitted from SERVER to CLIENT.
CLIENT: I have received it. Thank you!
SERVER: You’re welcome! Would love to stay on the line and chat, but I have other
requests to process. Bye!

Clients contact servers with requests, and servers respond with data. But what is a server
and what is a client?
Web servers are Internet-connected computers running server software, so called be‐
cause they serve web documents as requested. Servers are typically always on and always
connected, but web developers often also run local servers, meaning they run on the
same computer that you’re working on. Local means here; remote means somewhere
else, on any computer but the one right in front of you.
There are lots of different server software packages, but Apache is the most common.
Web server software is not pretty, and no one ever wants to look at it.
In contrast, web browsers can be very pretty, and we spend a lot of time looking at them.
Regular people recognize names like Firefox, Safari, Chrome, and Internet Explorer, all
of which are browsers or web clients.
Every web page, in theory, can be identified by its URL (Uniform Resource Locator) or
URI (Uniform Resource Identifier). Most people don’t know what URL stands for, but
they recognize one when they see it. By obsolete convention, URLs commonly begin
with www, as in http://www.calmingmanatee.com, but with a properly configured serv‐
er, the www part is wholly unnecessary.
Complete URLs consist of four parts:

• An indication of the communication protocol, such as HTTP or HTTPS


• The domain name of the resource, such as calmingmanatee.com
• The port number, indicating over which port the connection to the server should
be attempted
• Any additional locating information, such as the path of the requested file, or any
query parameters

A complete URL, then, might look like this: http://alignedleft.com:80/tutorials/d3/.


Typically, the port number is excluded, as web browsers will try to connect over port 80
by default. So the preceding URL is functionally the same as the following: http://
alignedleft.com/tutorials/d3/
Note that the protocol is separated from the domain name by a colon and two forward
(regular) slashes. Why two slashes? No reason. The inventor of the Web regrets the error.

16 | Chapter 3: Technology Fundamentals


HTTP stands for Hypertext Transfer Protocol, and it’s the most common protocol for
transferring web content from server to client. The “S” on the end of HTTPS stands for
Secure. HTTPS connections are used whenever information should be encrypted in
transit, such as for online banking or e-commerce.
Let’s briefly step through the process of what happens when a person goes to visit a
website.

1. User runs the web browser of her choice, then types a URL into the address bar,
such as alignedleft.com/tutorials/d3/. Because she did not specify a protocol, HTTP
is assumed, and “http://” is prepended to the URL.
2. The browser then attempts to connect to the server behind alignedleft.com across
the network, via port 80, the default port for HTTP.
3. The server associated with alignedleft.com acknowledges the connection and is
taking requests. (“I’ll be here all night.”)
4. The browser sends a request for the page that lives at /tutorials/d3/.
5. The server sends back the HTML content for that page.
6. As the client browser receives the HTML, it discovers references to other files needed
to assemble and display the entire page, including CSS stylesheets and image files.
So it contacts the same server again, once per file, requesting the additional infor‐
mation.
7. The server responds, dispatching each file as needed.
8. Finally, all the web documents have been transferred over. Now the client performs
its most arduous task, which is to render the content. It first parses through the
HTML to understand the structure of the content. Then it reviews the CSS selectors,
applying any properties to matched elements. Finally, it plugs in any image files and
executes any JavaScript code.

Can you believe that all that happens every time you click a link? It’s a lot more com‐
plicated than most people realize, but it’s important to understand that client/server
conversations are fundamental to the Web.

HTML
Hypertext Markup Language is used to structure content for web browsers. HTML is
stored in plain text files with the .html suffix. A simple HTML document looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

HTML | 17
<h1>Page Title</h1>
<p>This is a really interesting paragraph.</p>
</body>
</html>
HTML is a complex language with a rich history. This overview will address only the
current iteration of HTML (formerly known as HTML5) and will touch on only what
is immediately relevant for our practice with D3.

Content Plus Structure


The core function of HTML is to enable you to “mark up” content, thereby giving it
structure. Take, for example, this raw text:
Amazing Visualization Tool Cures All Ills A new open-source tool designed for
visualization of data turns out to have an unexpected, positive side effect:
it heals any ailments of the viewer. Leading scientists report that the tool,
called D3000, can cure even the following symptoms: fevers chills general
malaise It achieves this end with a patented, three-step process. Load in data.
Generate a visual representation. Activate magic healing function.
Reading between the lines, we can infer that this is a very exciting news story. But as
unstructured content, it is very hard to read. By adding structure, we can differentiate
between the headline, for example, and the body of the story.

Amazing Visualization Tool Cures All Ills


A new open-source tool designed for visualization of data turns out to have an unexpec‐
ted, positive side effect: it heals any ailments of the viewer. Leading scientists report that
the tool, called D3000, can cure even the following symptoms:

• fevers
• chills
• general malaise

It achieves this end with a patented, three-step process.

1. Load in data.
2. Generate a visual representation.
3. Activate magic healing function.

That has the same raw text content, but with a visual structure that makes the content
more accessible.
HTML is a tool for specifying semantic structure, or attaching hierarchy, relationships,
and meaning to content. (HTML doesn’t address the visual representation of a

18 | Chapter 3: Technology Fundamentals


document’s structure—that’s CSS’ job.) Here is our story with each chunk of content
replaced by a semantic description of what that content is.

Headline
Paragraph text

• Unordered list item


• Unordered list item
• Unordered list item

Paragraph text

1. Numbered list item


2. Numbered list item
3. Numbered list item

This is the kind of structure we specify with HTML markup.

Adding Structure with Elements


“Marking up” is the process of adding tags to create elements. HTML tags begin with <
and end with >, as in <p>, which is the tag indicating a paragraph of text. Tags usually
occur in pairs, in which case adding an opening and closing pair of tags creates a new
element in the document structure.
Closing tags are indicated with a slash that closes or ends the element, as in </p>. Thus,
a paragraph of text may be marked up like the following:
<p>This is a really interesting paragraph.</p>

Some elements can be nested. For example, here we use the em element to add emphasis.
<p>This is a <em>really</em> interesting paragraph.</p>

Nesting elements introduces hierarchy to the document. In this case, em is a child of p


because it is contained by p. (Conversely, p is em’s parent.)
When elements are nested, they cannot overlap closures of their parent elements, as
doing so would disrupt the hierarchy. For example:
<p>This could cause <em>unexpected</p>
<p>results</em>, and is best avoided.</p>

HTML | 19
Some tags never occur in pairs, such as the img element, which references an image file.
Although HTML no longer requires it, you will sometimes see such tags written in self-
closing fashion, with a trailing slash before the closing bracket:
<img src="photo.jpg" />
As of HTML5, the self-closing slash is optional, so the following code is equivalent to
the preceding code:
<img src="photo.jpg">

Common Elements
There are hundreds of different HTML elements. Here are some of the most common.
We’ll cover additional elements in later chapters. (Reference the excellent Mozilla De‐
veloper Network documentation for a complete listing.)
<!DOCTYPE html>
The standard document type declaration. Must be the first thing in the document.
html
Surrounds all HTML content in a document.
head
The document head contains all metadata about the document, such as its title
and any references to external stylesheets and scripts.
title
The title of the document. Browsers typically display this at the top of the browser
window and use this title when bookmarking a page.
body
Everything not in the head should go in the body. This is the primary visible content
of the page.
h1, h2, h3, h4
These let you specify headings of different levels. h1 is a top-level heading, h2 is
below that, and so on.
p
A paragraph!
ul, ol, li
Unordered lists are specified with ul, most often used for bulleted lists. Ordered
lists (ol) are often numbered. Both ul and ol should include li elements to specify
list items.
em
Indicates emphasis. Typically rendered in italics.

20 | Chapter 3: Technology Fundamentals


strong
Indicates additional emphasis. Typically rendered in boldface.
a
A link. Typically rendered as underlined, blue text, unless otherwise specified.
span
An arbitrary span of text, typically within a larger containing element like p.
div
An arbitrary division within the document. Used for grouping and containing re‐
lated elements.
Our earlier example could be given semantic structure by marking it up using some of
these element’s tags:
<h1>Amazing Visualization Tool Cures All Ills</h1>
<p>A new open-source tool designed for visualization of data turns out to have
an unexpected, positive side effect: it heals any ailments of the viewer.
Leading scientists report that the tool, called D3000, can cure even the
following symptoms:</p>
<ul>
<li>fevers</li>
<li>chills</li>
<li>general malaise</li>
</ul>
<p>It achieves this end with a patented, three-step process.</p>
<ol>
<li>Load in data.</li>
<li>Generate a visual representation.</li>
<li>Activate magic healing function.</li>
</ol>
When viewed in a web browser, that markup is rendered as shown in Figure 3-1.

HTML | 21
Figure 3-1. Typical default rendering of simple HTML

Notice that we specified only the semantic structure of the content; we didn’t specify
any visual properties, such as color, type size, indents, or line spacing. Without such
instructions, the browser falls back on its default styles, which, frankly, are not too
exciting.

Attributes
All HTML elements can be assigned attributes by including property/value pairs in the
opening tag.
<tagname property="value"></tagname>
The name of the property is followed by an equals sign, and the value is enclosed within
double quotation marks.
Different kinds of elements can be assigned different attributes. For example, the a link
tag can be given an href attribute, whose value specifies the URL for that link. (href is
short for “HTTP reference.”)
<a href="http://d3js.org/">The D3 website</a>

Some attributes can be assigned to any type of element, such as class and id.

Classes and IDs


Classes and IDs are extremely useful attributes, as they can be referenced later to identify
specific pieces of content. Your CSS and JavaScript code will rely heavily on classes and
IDs to identify elements. For example:

22 | Chapter 3: Technology Fundamentals


<p>Brilliant paragraph</p>
<p>Insightful paragraph</p>
<p class="awesome">Awe-inspiring paragraph</p>
These are three very uplifting paragraphs, but only one of them is truly awesome, as I’ve
indicated with class="awesome". The third paragraph becomes part of a class of awe‐
some elements, and it can be selected and manipulated along with other class members.
(We’ll get to that in a moment.)
Elements can be assigned multiple classes, simply by separating them with a space:
<p class="uplifting">Brilliant paragraph</p>
<p class="uplifting">Insightful paragraph</p>
<p class="uplifting awesome">Awe-inspiring paragraph</p>

Now, all three paragraphs are uplifting, but only the last one is both uplifting and
awesome.
IDs are used in much the same way, but there can be only one ID per element, and each
ID value can be used only once on the page. For example:
<div id="content">
<div id="visualization"></div>
<div id="button"></div>
</div>

IDs are useful when a single element has some special quality, like a div that functions
as a button or as a container for other content on the page.
As a general rule, if there will be only one such element on the page, you can use an
id. Otherwise, use a class.

Class and ID names cannot begin with numerals; they must begin with
alphabetic characters. So id="1" won’t work, but id="item1" will. The
browser will not give you any errors; your code simply won’t work, and
you will go crazy trying to figure out why.

Comments
As code grows in size and complexity, it is good practice to include comments. These
are friendly notes that you leave for yourself to remind you why you wrote the code the
way you did. If you are like me, you will revisit projects only weeks later and have lost
all recollections of it. Commenting is an easy way to reach out and provide guidance
and solace to your future (and very confused) self.
In HTML, comments are written in the following format:
<!-- Your comment here -->

Anything between the <!-- and --> will be ignored by the web browser.

HTML | 23
DOM
The term Document Object Model refers to the hierarchical structure of HTML. Each
pair of bracketed tags (or, in some cases, a single tag) is an element, and we refer to
elements’ relative relationships to each other in human terms: parent, child, sibling,
ancestor, and descendant. For example, in this HTML:
<html>
<body>
<h1>Breaking News</h1>
<p></p>
</body>
</html>

body is the parent element to both of its children, h1 and p (which are siblings to each
other). All elements on the page are descendants of html.
Web browsers parse the DOM to make sense of a page’s content. As coders building
visualizations, we care about the DOM, because our code must navigate its hierarchy
to apply styles and actions to its elements. We don’t want to make all the div elements
blue; we need to know how to select just the divs of the class sky and make them blue.

Developer Tools
In the olden days, the web development process went like this:

1. Write some code in a text editor.


2. Save the files.
3. Switch to a browser window.
4. Reload the page, and see if your code worked.
5. If it didn’t work, take a guess at what went wrong inside the magical black box of
the web browser, then go back to step 1.

Browsers were notoriously secretive about what went on inside the rendering engine,
which made debugging a total nightmare. (Seriously, in the late 1990s and early 2000s,
I literally had nightmares about this.) Fortunately, we live in a more enlightened age,
and every modern-day browser has built-in developer tools that expose the inner work‐
ings of the beast and enable us to poke around under the hood (to mix incompatible
metaphors).
All this is to say that developer tools are a big deal and you will rely on them heavily to
both test your code and, when something breaks, figure out what went wrong.
Let’s start with the simplest possible use of the developer tools: viewing the raw source
code of an HTML page (see Figure 3-2).

24 | Chapter 3: Technology Fundamentals


Every browser supports this, although different browsers hide this option in different
places. In Chrome 23.0, it’s under View→Developer→View Source. In Firefox 17.0, look
under Tools→Web Developer→Page Source. In Safari 6.0, it’s under Develop→Show
Page Source (although you must first set the “Develop” menu to display under Sa‐
fari→Preferences→Advanced). Going forward, I’m going to assume that you’re using
the newest version of whatever browser you choose.

Figure 3-2. Looking at the source code in a new window

That gets you the raw HTML, but if any D3 or JavaScript code has been executed, the
current DOM may be vastly different.
Fortunately, your browser’s developer tools enable you to see the current state of the
DOM. And, again, the developer tools are different in every browser. In Chrome, find
them under View→Developer→Developer Tools. In Firefox, try Tools→Web Developer.
In Safari, first enable the developer tools (in Safari→Preferences→Advanced). Then, in
the Develop menu, choose Show Web Inspector. In any browser, you can also use the
corresponding keyboard shortcut (as shown adjacent to the menu item) or right-click
and choose “inspect element” or something similar.
Until recently, Safari and Chrome shared the same developer tools, but with Safari 6.0,
Apple completely redesigned their dev tools, much to the dismay of many web-
developing Safari fans. (The new tools are very hard to navigate, and I don’t think I’m
the only one who feels that way.) Whichever browser you use might look a bit different
from my screenshots, but the functionality will be very similar.

Developer Tools | 25
Figure 3-3 shows the Elements tab of Chrome’s web inspector. Here we can see the
current state of the DOM. This is useful because your code will modify DOM elements
dynamically. In the web inspector, you can watch elements as they change.
Download from Wow! eBook <www.wowebook.com>

Figure 3-3. Chrome’s web inspector

If you look closely, you’ll already see some differences between the raw HTML and the
DOM, including the fact that Chrome generated the required html, head, and body
elements. (I was lazy and didn’t include them in my original HTML.)

26 | Chapter 3: Technology Fundamentals


One more thing: why am I focusing on Chrome, Firefox, and Safari? Why not Internet
Explorer, Opera, or the many other browsers out there? For one, it’s best to develop your
projects using a browser with the broadest support for web standards. Internet Explorer
made huge progress with versions 9 and 10, but Chrome, Firefox, and Safari are un‐
derstood to have the broadest standards support, and they are updated more frequently.
Second, you’re going to spend a lot of time using the developer tools, so you should
develop with a browser that has tools you enjoy using. I was pretty devoted to Safari
until the 6.0 update changed everything. Now I’m going back and forth between Chrome
and Firefox’s new dev tools. I recommend you try them all and decide what works best
for you.

Rendering and the Box Model


Rendering is the process by which browsers, after parsing the HTML and generating the
DOM, apply visual rules to the DOM contents and draw those pixels to the screen.
The most important thing to keep in mind when considering how browsers render
content is this: to a browser, everything is a box.
Paragraphs, divs, spans—all are boxes in the sense that they are two-dimensional rec‐
tangles, with properties that any rectangle can have, such as width, height, and positions
in space. Even if something looks curved or irregularly shaped, rest assured, to the
browser, it is merely another rectangular box.
You can see these boxes with the help of the web inspector. Just mouse over any element,
and the box associated with that element is highlighted in blue, as shown in Figure 3-4.

Rendering and the Box Model | 27


Figure 3-4. Inspector with element box highlighted

There’s a lot of information about the ul unordered list here. Note that the list’s total
dimensions (width and height) are shown in the yellow box at the element’s lower-left
corner. Also, the list’s position in the DOM hierarchy is indicated in the lower-left corner
of the inspector: html > body > ul.
The box for the ul expands to fill the width of the entire window because it is a block-
level element. (Note how under “Computed Style” is listed display: block.) This is in
contrast to inline elements, which rest in line with each other, not stacked on top of each
other like blocks. Common inline elements include strong, em, a, and span.
By default, block-level elements expand to fill their container elements and force any
subsequent sibling elements further down the page. Inline elements do not expand to
fill extra space, and happily exist side by side, next to their fellow inline neighbors.
(Discussion question: what kind of element would you rather be?)

28 | Chapter 3: Technology Fundamentals


CSS
Cascading Style Sheets are used to style the visual presentation of DOM elements. A
simple CSS stylesheet looks like the following:
body {
background-color: white;
color: black;
}
CSS styles consist of selectors and properties. Selectors are followed by properties, grou‐
ped in curly brackets. A property and its value are separated by a colon, and the line is
terminated with a semicolon, like the following:
selector {
property: value;
property: value;
property: value;
}
The same properties can be applied to multiple selectors at once by separating the se‐
lectors with a comma, as in the following:
selectorA,
selectorB,
selectorC {
property: value;
property: value;
property: value;
}

For example, you might want to specify that both p paragraphs and li list items should
use the same font size, line height, and color.
p,
li {
font-size: 12px;
line-height: 14px;
color: orange;
}
Collectively, this whole chunk of code (selectors and bracketed properties) is called a
CSS rule.

Selectors
D3 uses CSS-style selectors to identify elements on which to operate, so it’s important
to understand how to use them.
Selectors identify specific elements to which styles will be applied. There are several
different kinds of selectors. We’ll use only the simplest ones in this book.

CSS | 29
Random documents with unrelated
content Scribd suggests to you:
own modest sphere I well remember the refreshment I occasionally
derived from five minutes’ sleep on a deal table, with Babbage and
Callet’s Logarithms under my head for a pillow. On a certain day,
under grave penalties, certain levels had to be finished, and this
particular day was one of agony to me. The atmosphere seemed
filled with mocking demons, laughing at the vanity of my efforts to
get the work done. My levelling staves were snapped, and my
theodolite was overthrown by the storm. When things are at their
worst a kind of anger often takes the place of fear. It was so in the
present instance; I pushed doggedly on, and just at nightfall, when
barely able to read the figures on my levelling staff, I planted my last
‘benchmark’ on a tombstone in Haworth Churchyard. Close at hand
was the vicarage of Mr. Brontë, where the genius was nursed which
soon afterwards burst forth and astonished the world. It was a time
of mad unrest—of downright money mania. In private residences
and public halls, in London reception rooms, in hotels and the
stables of hotels, among gipsies and costermongers, nothing was
spoken of but the state of the share market, the prospects of
projected lines, the good fortune of the ostler or potboy who by a
lucky stroke of business had cleared £10,000. High and low, rich and
poor, joined in the reckless game. During my professional connection
with railways I endured three weeks’ misery. It was not defeated
ambition; it was not a rejected suit; it was not the hardship endured
in either office or field; but it was the possession of certain shares
purchased in one of the lines then afloat. The share list of the day
proved the winding-sheet of my peace of mind. I was haunted by
the Stock Exchange. I became at last so savage with myself that I
went to my brokers and put away, without gain or loss, the shares
as an accursed thing.”
When in Halifax in 1845 he attended a lecture which was
delivered by Mr. George Dawson, and which appeared to make a
lasting impression on his mind. That popular lecturer then defined
duty as a debt owed; and with reference to the Chartist doctrine of
“levelling” then in vogue, he said: Supposing two men to be equal at
night, and that one rises at six while the other sleeps till nine, what
becomes of the gospel of levelling then? The Professor regarded
these as the words of Nature, and there was, according to his
impression, “a kindling vigour in the lecturer’s words that must have
strengthened the sense of duty in the minds of those who heard
him.”
It was while working in Yorkshire about that time that he first met
Mr. T. A. Hirst, then an articled pupil, who became one of his most
intimate friends, and who afterwards became Professor of
Mathematics in University College, London. At that time, too, Sir
John Hawkshaw, who afterwards was Prof. Tyndall’s successor as
President of the British Association, was chief engineer on the
Manchester and Leeds Railway, and it was in his Manchester office
that Tyndall spent the last days of his railway life. A calm followed
the storm of competition just described; work became scarce, and
the prospects of engineers were once more overcast.
In these circumstances he accepted, in 1847, an appointment as
a teacher in Queenswood College, Hampshire. The well-known
Socialist reformer, Robert Owen, and his disciples built that college—
a fine edifice occupying a healthy position—and called it Harmony
Hall, as it was meant to inaugurate the millennium; the letters “C. of
M” (commencement of millennium) being inserted in flint in the
brickwork of the house. Around this college were large farms, where
lessons were given by Prof. Tyndall to the more advanced students
on the subjects which he had mastered in his previous labours. With
teaching he combined self-improvement. The chemical laboratory
was under the charge of Dr. Frankland, with whom he soon became
friendly. In order to spend part of his time in study in the chemical
laboratory, Tyndall relinquished part of his salary, and there he laid
the foundations of that knowledge of physical science which was
destined afterward to be his own passport to fame and to afford
delight to many thousands of his fellowmen. He was also very
successful as a teacher in Queenswood College. He is said to have
exercised a kind of magnetic influence over his students, and such
was their faith in him that when any disturbances arose among them
he was invariably called upon to settle them, and he did so merely
by the power of moral influence and force of character. As to his
impressions of life at Queenswood, the Professor says:—
“Schemes like Harmony Hall look admirable upon paper; but,
inasmuch as they are formed with reference to an ideal humanity,
they go to pieces when brought into collision with the real one. At
Queenswood, I learned, by practical experience, that two factors
went to the formation of a teacher. In regard to knowledge he must,
of course, be master of his work. But knowledge is not all. There
might be knowledge without power—the ability to inform without the
ability to stimulate. Both go together in the true teacher. A power of
character must underlie and enforce the work of the intellect. There
were men who could so rouse and energise their pupils—so call forth
their strength and the pleasure of its exercise—as to make the
hardest work agreeable. Without this power it is questionable
whether the teacher could ever really enjoy his vocation—with it, I
do not know a higher, nobler, and more blessed calling than that of
the man who, scorning the cramming so prevalent in our day,
converts the knowledge he imparts into a lever, to lift, exercise, and
strengthen the growing minds committed to his care.”
After pursuing their scientific studies together for some time, both
Tyndall and Frankland began to think of extending the range of their
scientific culture. But that could not then be done in England. In
1845 a man could not easily get first-class instruction in practical
chemistry and the other physical sciences that were then making
great strides forward. Between 1840 and 1850 Germany assumed
the lead in these sciences. In that country science then organised
itself on a vast scale, and from that time to this it has been growing
there at a most extraordinary rate; indeed, Prof. Huxley declared in
1884 that in the whole history of the world there has never been
such a tremendous amount of organised energy bestowed in the
development of physical science as in Germany.
“At the time here referred to,” says Professor Tyndall, “I had
emerged from some years of hard labour the fortunate possessor of
two or three hundred pounds. By selling my services in the dearest
market during the railway madness the sum might, without
dishonour, have been made a large one; but I respected ties which
existed prior to the time when offers became lavish and temptation
strong. I did not put my money in a napkin, but cherished the design
of spending it in study at a German university. I had heard of
German science, while Carlyle’s references to German philosophy
and literature caused me to regard them as a kind of revelation from
the gods. Accordingly, in the autumn of 1848, Frankland and I
started for the land of universities, as Germany is often called. They
are sown broadcast over the country, and can justly claim to be the
source of an important portion of Germany’s present greatness.
“Our place of study was the town of Marburg, in Hesse-Cassel,
and a very picturesque town Marburg is. It clambers pleasantly up
the hillsides, and falls as pleasantly towards the Lahn. On a May day,
when the orchards are in blossom, and the chestnuts clothed with
their heavy foliage, Marburg is truly lovely. It is the same town in
which my great namesake, when even poorer than myself, published
his translation of the Bible. I lodged in the plainest manner in a
street which perhaps bore an appropriate name while I dwelt there.
It was called the Ketzerbach—the heretics’ brook—from a little
historical rivulet running through it. I wished to keep myself clean
and hardy, so I purchased a cask and had it cut in two by a
carpenter. That cask, filled with spring-water over night, was placed
in my small bedroom, and never during the years that I spent there,
in winter or in summer, did the clock of the beautiful
Elizabethekirche, which was close at hand, finish striking the hour of
six in the morning before I was in my tub. For a good portion of the
time I rose an hour and a-half earlier than this, working by lamp-
light at the Differential Calculus when the world was slumbering
around me. I risked this breach of my pursuits and this expenditure
of my time and money, not because I had any definite prospect of
material profit in view, but because I thought the cultivation of the
intellect important; because, moreover, I loved my work, and
entertained a sure and certain hope that armed with knowledge one
can successfully fight one’s way through the world. I ought not to
omit one additional motive by which I was upheld at the time here
referred to—that was the sense of duty. Every young man of high
aims must, I think, have a spice of this principle within him. There
are sure to be hours in his life when his outlook will be dark, his
work difficult, and his intellectual future uncertain. Over such
periods, when the stimulus of success is absent, he must be carried
by his sense of duty. It may not be so quick an incentive as glory,
but it is a nobler one, and gives a tone to character which glory
cannot impart. That unflinching devotion to work, without which no
real eminence in science is now attainable, implies the writing at
certain times of stern resolve upon the student’s character: ‘I work
not because I like work, but because I ought to work.’ At Marburg
my study was warmed by a large stove. At first I missed the gleam
and sparkle from flame and ember, but I soon became accustomed
to the obscure heat. At six in the morning a small milch-brod and a
cup of tea were taken to me. The dinner hour was one, and for the
first year or so I dined at an hotel. In those days living was cheap in
Marburg. Dinner consisted of several courses, roast and boiled, and
finished up with sweets and dessert. The cost was a pound a month,
or about eightpence per dinner. I usually limited myself to one
course, using even that in moderation, being convinced that eating
too much was quite as sinful, and almost as ruinous, as drinking too
much. By attending to such things I was able to work without
weariness for sixteen hours a day. My going to Germany had been
opposed by some of my friends as quixotic, and my life there might,
perhaps, be not unfairly thus described. I did not work for money; I
was not even spurred by ‘the last infirmity of noble minds.’ I had
been reading Fichte, and Emerson, and Carlyle, and had been
infected by the spirit of these great men, the Alpha and Omega of
whose teaching was loyalty to duty. Higher knowledge and greater
strength were within reach of the man who unflinchingly enacted his
best insight.”
Even a statue was capable of impressing this truth upon him. But
it was the statue of the man who said of his own features: “This is
the face of a man who has struggled energetically”—the man of
whose portrait Carlyle says: “Reader, to thee thyself, even now, he
has one counsel to give, the secret of his whole poetic alchemy.
Think of living! Thy life, were thou the pitifullest of all the sons of
earth, is no idle dream, but a solemn reality. It is thy own; it is all
thou hast to front eternity with. Work, then, even as he has done
and does—Like a star, unhasting yet unresting.” Equally impressive was
the effect produced on Professor Tyndall by even the sight of the
form of such a man. Finding himself one fine summer evening
standing beside a statue of Goethe in a German city, the
contemplation of this work of art, which he considered the most
suitable memorial for a great man, excited a motive force within his
mind, which he thought no purely material influence could generate.
“There was then,” he says, “labour before me of the most arduous
kind. There were formidable practical difficulties to be overcome,
and very small means wherewith to overcome them; and yet I felt
that no material means could, as regards the task I had undertaken,
plant within me a resolve comparable with that which the
contemplation of this statue of Goethe was able to arouse.”
From his youth Tyndall appeared to have a remarkable power, not
only of attracting friends, but of retaining them. The circumstances
under which he early became acquainted with his life-long friends,
General Wynne and Professor Hirst, have already been mentioned.
Hirst was scarcely sixteen years of age when he became acquainted
with Tyndall, who was ten years older. Though they stood in the
relation of pupil and teacher, their intimacy ripened into an enduring
friendship which separation heightened rather than dissolved. An
incident that occurred while Tyndall was studying at Marburg affords
honourable evidence of this fact. The death of a relative in 1849
made Hirst the possessor of a small patrimony, which he determined
to divide between himself and his former teacher. He accordingly
pressed Professor Tyndall to accept one half of his small fortune, but
much to his disappointment Tyndall would have none of it.
Entreaties to accept it for friendship’s sake were unavailing, but
friendship, like necessity, can invent strange means for attaining its
end. Hirst took counsel with a German banker as to a way of
conveying the money to his friend, and soon a device was carried
out, by means of which the devotee of science had to sacrifice his
self-denial on the altar of friendship. While at work one morning in
his lodgings in Marburg the postman brought him a heavy roll closely
packed and sealed, which, to his astonishment, contained all sorts of
German coins amounting to 20l. sterling, a considerable gratuity for
a student to receive in those days. He had no alternative but to
accept it. On a subsequent occasion when Tyndall left Marburg to
visit England another friend of his youth, General Wynne, offered to
replenish his exchequer, which he feared must be nearly empty, but
the offer was declined with assurances that such generous
assistance was unnecessary.
CHAPTER II.
“No man ever yet made great discoveries in Science who
was not impelled by an abstracted love.”—Sir Humphry Davy.

At the time when Professor Tyndall was studying at Marburg


University, the principal figure there was Bunsen, who had been
appointed Professor of Chemistry in 1838. He was a profound
chemist, and his fame as a lecturer was so eminent as to attract
many foreign students. A prolific discoverer, and peculiarly happy in
his manner of demonstrating his scientific teaching, he soon
fascinated the ardent minds of the two students from Queenswood.
For two years Tyndall attended his chemical lectures. Indeed he
learned German chiefly by listening to Bunsen. He has himself stated
that Bunsen treated him like a brother, giving his time, space, and
appliances, for the benefit of his studies. The subject which most
attracted Tyndall’s attention was electro-chemistry, upon which
Bunsen delivered an admirable course of lectures in 1848. The whole
principle of the voltaic pile was thus explained to him in a masterful
manner. He also made himself acquainted with chemical analyses,
both quantitative and qualitative. He displayed no less zeal in the
study of mathematics. For a considerable period he got private
lessons from Professor Stegmann, under whose tuition he worked
through analytical geometry of two and three dimensions, the
Differential and Integral Calculus, and part of the Calculus of
Variations.
His first scientific paper was a mathematical essay on screw
surfaces, respecting which he says:—“Professor Stegmann gave me
the subject of my dissertation when I took my degree: its title in
English was, ‘On a Screw Surface with Inclined Generatrix, and on
the Conditions of Equilibrium on such Surfaces.’ I resolved that if I
could not, without the slightest aid accomplish the work from
beginning to end it should not be accomplished at all. Wandering
among the pine wood and pondering the subject, I became more
and more master of it; and when my dissertation was handed in to
the Philosophical Faculty it did not contain a thought that was not
my own.”
But the man whose acquaintance at Marburg appeared to
exercise most influence over his career was Dr. Knoblauch, who had
just come thither from Berlin as extraordinary Professor of Physics,
and who had already distinguished himself by his researches in
radiant heat. He illustrated his lectures with a choice collection of
apparatus brought from Berlin; and he not only suggested to Tyndall
an exhaustive series of experiments bearing on a newly-discovered
principle of physics, but supplied him with the necessary apparatus,
and placed his own cabinet at his disposal for that purpose. The
subject of investigation was diamagnetism.
Faraday’s discoveries and experiments in magnetism were then
attracting the attention of the scientific world. He had shown in 1830
that by moving a magnet within the hollow of a coil of copper wire
an electrical current was produced in the wire. This was a startling
and pregnant discovery. Taking six hundred feet of insulated copper
wire and winding it into a large vertical coil, he arranged the two
ends of the wire into a small coil a little distance away from the large
coil, and immediately above this small coil he suspended a balanced
compass needle by a silk thread. Then, on dropping a bar magnet,
or piece of iron magnetised, into the large coil, the needle, which
was pointing towards the North Pole, instantly swung round,
evidently impelled by magnetic force; when, again, the bar magnet
was raised out of the hollow of the large coil, the needle moved
round in the opposite direction; while it remained motionless so long
as the bar magnet was at rest either inside or outside the coil. It
thus appeared that an electrical current could be produced by the
movement of the bar magnet—by dropping it into the coil or taking
it out; and the current so produced he called an induced current.
This operation is called magneto-electric induction. In 1845 Faraday
greatly extended his magnetic discoveries. He not only established
the magnetic condition of all matter by showing that every known
body or thing could be influenced by magnetism, but he discovered
a new property of magnetism, which he called diamagnetism. This
was considered his greatest discovery.
By suspending bodies of an elongated form between the ends or
poles of powerful magnets, he found that every substance was
attracted or repelled from the magnetic poles; and he divided all
bodies into two great classes, called magnetic and diamagnetic. The
way in which a piece of iron is attracted by the poles or ends of a
horseshoe magnet is a familiar illustration of the action of magnetic
bodies, and the position that such bodies assume, pointing in a line
from one pole to the other, he termed axial. On the other hand,
diamagnetic bodies were those which, when freely suspended within
the influence of the magnet, assumed a position at right angles to
the line joining the poles of a magnet, or to the magnetic meridian;
in other words, magnetic bodies pointed axially from pole to pole, or
north and south; while diamagnetic bodies pointed east and west, or
in an equatorial direction. Bismuth is a conspicuous example of
diamagnetic substances. Scientific curiosity soon became excited as
to the exact nature of the diamagnetic force in relation to crystals,
some of which behaved in a mysterious manner between the poles
of a magnet. Professor Plücker, of Bonn, discovered that some
crystals formed of diamagnetic substances were not subject to the
diamagnetic force; and to account for this he attributed to crystals
an optical axis, upon which the poles of a magnet exercised a
peculiar force. Plücker brought this theory before the British
Association in 1848, and called it a new magnetic action. At the
close of the same year, Faraday told the Royal Society that he had
often been embarrassed by the anomalous magnetic results given by
small cylinders of bismuth, and after investigation he referred these
effects to the crystalline condition of the bismuth. In concluding his
lecture on this subject, Faraday said:—“How rapidly the knowledge
of molecular forces grows upon us, and how strikingly every
investigation tends to develop more and more their importance, and
their extreme attraction as an object of study. A few years ago,
magnetism was to us an occult power affecting only a few bodies:
now it is found to influence all bodies, and to possess the most
intimate relations with electricity, heat, chemical action, light,
crystallisation, and, through it, with the forces concerned in
cohesion.” He thought there was in crystals a directive impelling
force distinct from the magnetic and diamagnetic force.
Frequent conversations on this subject took place between
Knoblauch and Tyndall in Germany during 1849. Knoblauch
suggested that Tyndall should repeat the experiments of Plücker and
Faraday; and as this operation was proceeding they agreed to make
a joint inquiry into the deportment of crystals under the diamagnetic
force. They laboured long at the problem before attaining any
encouraging success. They examined the optical properties of
crystals as well as made magnetic experiments with them, a great
many experiments being made without discovering any new fact.
Eventually, however, they found that various crystals did not act in
accordance with the principles enunciated by Plücker, and the more
they worked at the subject the more clearly it appeared that the
deportment of certain bodies under the influence of magnetism was
due, not to the presence of some force previously unknown, but to
the crystalline structure of the substance under investigation, or as
Tyndall put it, to peculiarities of material aggregation. For example,
he showed that while a bar of iron attracted by a magnet sets itself
in a line from pole to pole, an iron bar made of an aggregate of
small bars sets itself in the opposite direction. Tyndall showed that
the cause of the latter bar assuming an equatorial position was
simply its mechanical structure, the small plates composing the
“aggregated” bar setting from pole to pole. He found that the same
law regulated the magnetic deportment of crystals, whose
mechanism or structure, however, was generally less evident.
In 1849 eminent natural philosophers were studying this subject
in England, France, and Germany, and it was expected that the
investigation of diamagnetic phenomena would rapidly throw some
new light upon the molecular forces which determine the conditions
of the material creation. In allusion to this expectation, Tyndall said
in 1850, that as nature acts by general laws, to which the terms
great and small are unknown, it cannot be doubted that the
modifications of magnetic force, exhibited by bits of copperas and
sugar in the magnetic field, display themselves on a large scale in
the crust of the earth itself, and as a lump of stratified grit, though a
magnetic material, could be made, on account of its planes of
stratification, to act as if it were diamagnetic, he suggested that this
element might have some influence in determining the varying
position of the magnetic poles of the earth—a subject which still
perplexes the scientific world. Not only has the north magnetic pole
gradually been changing its position, as shown by the records of
three centuries, but, according to Barlow, every place has a
magnetic pole and equator of its own; and according to Faraday the
earth is a great magnet, whose power, as estimated by Gauss, is
equal to that which would be conferred if every cubic yard of it
contained six one-pound magnets; the sum of the force being thus
equal to 8,464,000,000,000,000,000,000 such magnets. “The
disposition of this magnetic force is not regular,” said Faraday, “nor
are there any points on the surface which can be properly called
poles: still the regions of polarity are in high north and south
latitudes; and these are connected by lines of magnetic force (being
the lines of direction), which, generally speaking, rise out of the
earth in one (magnetic) hemisphere, and passing in various
directions over the equatorial regions into the other hemisphere,
there enter into the earth to complete the known circuit of power.”
It was in connection with his investigations on this subject that
Prof. Tyndall first saw Prof. Faraday. Returning from Marburg in 1850,
he called at the Royal Institution and sent in his card, together with
a copy of a paper he had prepared, giving the results of his
experiments on magne-crystallic action. Prof. Faraday conversed with
him for half-an-hour, and being then on the point of publishing one
of his papers on magne-crystallic action, he appended to it a
flattering reference to the notes which Tyndall had placed in his
hands.
Tyndall went back to Germany, where he worked for another year.
In the beginning of 1851 he went to Berlin, where, he says, Prof.
Magnus had made his name famous by physical researches of all
kinds. “On April 28th, 1851, I first saw this Professor on his own
doorstep in Berlin. His aspect won my immediate regard, which was
strengthened to affection by our subsequent intercourse. He gave
me a working place in his laboratory, and it was there I carried out
my investigations on diamagnetism and magnecrystallic action
published in the Philosophical Magazine for September, 1851. Among
the other eminent scientific men whom I met at Berlin was
Ehrenberg, with whom I had various conversations on microscopic
organisms. I also made the acquaintance of Riess, the foremost
exponent of frictional electricity, who more than once opposed to
Faraday’s radicalism his own conservatism as regarded electric
theory. Du Bois-Reymond was there at the time, full of power, both
physical and mental. His fame had been everywhere noised abroad
in connection with his researches on animal electricity. Du Bois-
Reymond became perpetual secretary to the Academy of Sciences,
Berlin. From Professor Magnus, and from Clausius, Wiedemann, and
Poggendorff, I received every mark of kindness, and formed with
some of them enduring friendships. Helmholtz was at this time in
Königsberg. He had written his renowned essay on the
“Conservation of Energy,” which I afterward translated. Helmholtz
had, too, just finished his experiments on the velocity of nervous
transmission, proving this velocity, which had previously been
regarded as instantaneous, or, at all events, as equal to that of
electricity, to be, in the nerves of the frog, only 93 ft. a second, or
about one-twelfth of the velocity of sound in air of the ordinary
temperature. In his own house I had the honour of an interview with
Humboldt. He rallied me on having contracted the habit of smoking
in Germany, his knowledge on this head being derived from my little
paper on a water-jet, where the noise produced by the rupture of a
film between the wet lips of a smoker is referred to. He gave me
various messages to Faraday, declaring his belief that he (Faraday)
had referred the annual and diurnal variation of the declination of
the magnetic needle to their true cause—the variation of the
magnetic condition of the oxygen of the atmosphere. I was
interested to learn from Humboldt himself that, though so large a
portion of his life had been spent in France, he never published a
French essay without having it first revised by a Frenchman. In
those days I not unfrequently found it necessary to subject myself to
a process which I called depolarisation. My brain, intent on its
subjects, used to acquire a set, resembling the rigid polarity of a
steel magnet. It lost the pliancy needful for free conversation, and to
recover this I used to walk occasionally to Charlottenburg or
elsewhere. From my experiences at that time I derived the notion
that hard thinking and fleet talking do not run together.”
Prof. Tyndall was exceptionally fortunate in getting so easily and
so early into the friendship of such eminent men of science. In those
days to form such eminent acquaintances was no small achievement
for a young Irishman; but on the other hand, he had fully earned
this distinction by the vigour and originality with which he attacked
the latest and most perplexing problem of that time. During the five
years that had elapsed since Faraday discovered diamagnetism, the
subject had been investigated by the greatest scientists in England,
France, and Germany, and no one had done so much to elucidate it
as Prof. Tyndall. In order to master that subject he began in
November, 1850, an investigation of the laws of magnetic
attractions. The laws of magnetic action at distances in comparison
with which the thickness of the magnet vanishes, had long been
known, but the laws of magnetic action at short distances, where
the thickness of the magnet comes fully into play, had not previously
been subjected to reliable experiments, and were therefore at that
time a perplexing matter of speculation. That desideratum he now
supplied. He found, among other things, that the mutual attraction
of a magnet and a sphere of soft iron, when both are separated by a
small fixed distance, is directly proportional to the square of the
strength of the magnet, and that the mutual attraction of a magnet
of constant strength and a sphere of soft iron is inversely
proportional to the distance between them.
Next year (1851) he published the results of further investigations
into the relations between magnetism and diamagnetism. He found
that the laws which govern magnetism and diamagnetism are
identical, that the superior attraction or repulsion of a mass in any
particular direction is due to the direction in which the material
particles are arranged most closely together, that the forces exerted
are attractive or repulsive according as the particles are magnetic or
diamagnetic, and that this law is applicable to matter in general.
A paper on “The Polarity of Bismuth,” which might be regarded as
a temporary instalment of his diamagnetic researches, ended with
the remark that during this inquiry he had changed his mind too
often to be over-confident now in the conclusion at which he had
arrived. Part of the time he was a hearty subscriber to the opinion of
Faraday that there existed no proof of diamagnetic polarity; and if,
he said, “I now differ from that great man, it is with an honest wish
to be set right, if through any unconscious bias of my own I have
been led either into errors of reasoning or mis-statements of fact.”
The theory of diamagnetism was still an apple of discord in the
scientific world; and although Prof. Tyndall used the language of
deference rather than of doubt, he did not allow the subject to
remain in a state of uncertainty. He continued his researches in
Berlin, in the private laboratory of Prof. Magnus, who afforded him
every possible facility for carrying on experiments, and took a lively
interest in the investigation. The result was the confirmation of his
previous impression that the action of crystals within the range of a
magnet’s influence (technically called the “magnetic field”) was due
to peculiarities of molecular arrangement. He found, for example,
that a crystal of carbonate of iron, which, when suspended in the
magnetic field, showed a certain deportment, could be pounded into
the finest dust, and the particles could be so put together again that
the mass would exhibit the same deportment as before.
Dr. Bence Jones, the Secretary of the Royal Institution, who had
heard of Tyndall in Berlin in 1851, afterwards invited him to give a
Friday evening lecture at the Royal Institution. “I went,” he says,
“not without fear and trembling, for the Royal Institution was to me
a kind of dragon’s den, where tact and strength would be necessary
to save me from destruction.” The lecture, which was delivered on
February 11th, 1853, was “On the Influence of Material Aggregation
upon the Manifestations of Force,” and it gave a beautiful and simple
exposition of the principles of magnetic and diamagnetic action
discovered by himself, the chief being that the line of greatest
density is that of strongest magnetic power. In the course of his
lecture he pointed out that anything which increases density
increases magnetic power; and upon that principle he contended
that the local action of the sun upon the earth’s crust must influence
in some degree the diurnal range of the magnetic needle, which
Faraday, on the other hand, attributed to the modification of our
atmosphere by the sun’s rays. While thus endeavouring to upset
Faraday’s theory, he concluded by saying: “This evening’s discourse
is, in some measure, connected with this locality, and thinking thus,
I am led to inquire wherein the true value of a scientific discovery
consists? Not in its immediate results alone, but in the prospect
which it opens to intellectual activity, in the hopes which it excites, in
the vigour which it awakens. The discovery which led to the results
brought before you to-night was of this character. That magnet was
the physical birthplace of these results; and if they possess any
value they are to be regarded as the returning crumbs of that bread
which in 1846 was cast so liberally upon the waters. I rejoice in the
opportunity here afforded me of offering my tribute to the greatest
worker of the age, and of laying some of the blossoms of that
prolific tree which he planted at the feet of the great discoverer of
diamagnetism.” At the conclusion of the lecture Faraday quitted his
usual seat, and crossing the theatre to the corner where the lecturer
stood, cordially shook him by the hand and congratulated him on his
success. A second lecture was delivered by him on June 3rd, 1853,
“On some of the Eruptive Phenomena of Iceland,” and a month later
he was unanimously elected Professor of Natural Philosophy in the
Royal Institution.
Some years previously he had read in a serial publication an
account of Davy’s experiments on radiant heat at the Royal
Institution, and he remembered ever after the longing then excited
in him to be able to do something of the same kind. Now he was to
occupy a position in which he should use, in his own lectures, the
same apparatus of which illustrations were given in the magazine
article that had fired his youthful ambition. To that position he was
promoted on the recommendation of Faraday, and respecting his
appointment he himself said: “I was tempted at the time to go
elsewhere, but a strong attraction drew me here. It was his
(Faraday’s) friendship that caused me to value my position here
more highly than any other.”
While the controversy respecting magnetic and diamagnetic
hypotheses was still raging, Faraday delivered a lecture at the Royal
Institution early in 1855 with the express object of cautioning the
investigators of scientific truths against placing too much confidence
on any hypothesis. He stated that every year of increased
experience had taught him more and more to distrust the theories
he had once adhered to; and his present impression with regard to
existing Magnetic and Electrical hypotheses was, that they were very
unsatisfactory, and that the propounders of them had been following
in a wrong track. As an instance of the obstacles which erroneous
hypotheses throw in the way of scientific discovery, he mentioned
the unsuccessful attempts that had been made in this country to
educe magnetism from electricity, until Oersted showed the simple
way. He said that the identity of magnetism and electricity had been
strongly impressed upon the minds of all: when he came to the
Royal Institution, as an assistant in the laboratory, he saw Davy,
Wollaston, and Young trying by every way that suggested itself to
them to produce magnetic effects from an electric current; but,
having their minds diverted from the true course by their existing
hypotheses, it did not occur to them to solve the point by holding a
wire, through which an electric current was passing, over a
suspended magnetic needle—the experiment by which Oersted
afterwards proved, by the deflection of the needle, the magnetic
property of an electric current.
Such cautions, however, did not deter Professor Tyndall from
defending the position he had taken up with regard to magnetism
and diamagnetism. He still maintained that the influence of structure
was supremely important,—that under the influence of magnetism or
electricity a normal diamagnetic bar always exhibits a deportment
precisely antithetical to that of a normal magnetic bar; but that, by
taking advantage of structure, it is possible to get diamagnetic bars
which exhibit precisely the same deportment as normal magnetic
ones, and magnetic bars which exhibit a deportment precisely
similar to normal diamagnetic ones. He showed numerous
experiments before the British Association in support of his
contention that the diamagnetic force is a polar one, with a direction
opposite to that of the force in ordinary magnetic bodies. Professor
William Thomson, who witnessed the experiments, certified the
success of every one of them; and stated that Professor Tyndall’s
discoveries in this domain of science had cleared away a mass of
rubbish and set things in their true light, adding that in many cases
he had repeated and varied Tyndall’s experiments, and had found
them to be true.
In 1855 he delivered the Bakerian lecture, in which he gave an
elaborate account of his latest researches respecting the phenomena
of diamagnetism. He was now firmly convinced, he said, that the
force that repelled a body was similar in character to that which
attracted a body; in other words, that diamagnetic bodies possess
the same kind of polarity, but in the opposite direction to that of
magnetic bodies. But the opponents of diamagnetic polarity, who
were not yet satisfied by the evidence he adduced, said that his
experiments were made with electrical conductors in which induced
currents could be formed that might account for the attractions and
repulsions. Professor Tyndall thought it would tend to settle the
question if he were to use a new kind of apparatus that would
obviate that objection. He therefore wrote to Professor Weber, of
Göttingen, whom Professor William Thomson described at the time
as the most profound and accurate of all experimenters, asking him
to devise more delicate and powerful means than had hitherto been
used in experimental tests. Weber not only devised a greatly
improved apparatus, but had it constructed under his own
superintendence at Leipsig.[2] With this apparatus Professor Tyndall
was able to satisfy the severest conditions proposed by those who
discredited the results of previous experiments. He then silenced
doubt by demonstrating that magnetism and diamagnetism stand, in
respect of polarity, on the same footing, with this difference, that the
one polarity is the inversion of the other. This diamagnetic polarity,
previously established in the case of bismuth, he showed to exist in
slate, marble, calcspar, sulphur, &c. He also established the polarity
of liquids, magnetic and diamagnetic. At the Royal Institution in
February, 1856, he showed that prisms of the same heavy glass as
that with which Faraday discovered the diamagnetic force, behaved
under the magnet in the same way as bismuth; and this evidence
was admitted to be conclusive by the opponents of diamagnetic
polarity. The controversy thereafter subsided.
His chief papers recording his most important investigations in
connection with diamagnetism were afterwards collected into a
volume entitled Researches on Diamagnetism and Magnecrystallic
Action.
In 1855 Professor Tyndall was appointed Examiner under the
Council for Military Education, and an incident which occurred shortly
afterwards illustrated the confidential relations into which his
intimacy with Faraday had ripened, as well as the independence of
character which distinguished both. Being strongly impressed with
the advantage of increasing the knowledge of physical science given
to artillery officers and engineers, Professor Tyndall advocated a
more liberal recognition of scientific attainments in their
examinations. At that time a committee of the British Association
was endeavouring to get the British Government to recognise the
claims of science; and in reply to inquiries made by that committee
as to the expediency of offering inducements for the acquisition of
science and of offering orders and decorations as rewards for
proficiency, Professor Faraday said: “I cannot say that I have not
valued such distinctions; on the contrary, I esteem them very highly;
but I don’t think I have ever worked for, or sought after, them.” Lord
Harrowby, in his address as President of the British Association, said
that the State had till recently done absolutely nothing for the
promotion of science; and it was remarked as a strange
circumstance that though there were then in the Cabinet the
President and President-elect of the British Association, it was
considered too hazardous to apply to the Government for money for
scientific purposes. While this neglect of science was being freely
discussed a number of well-instructed young men were sent from
Trinity College, Dublin, to compete at the Woolwich examinations in
1856 for appointments in the artillery and engineers, and their
scientific knowledge appeared so creditable that Professor Tyndall
thought it unnecessary to say anything about it. His colleagues, on
the other hand, sent in as usual brief reports with their returns
calling attention to the chief features of the examination, and a
leader in the Times pointed out that the concurrent testimony of the
examiners was that, both in mathematics and classics, the
candidates showed a marked improvement, but that on other points
they broke down. This appeared to Professor Tyndall an unjust
reflection upon their scientific attainments, which were thus ignored.
He accordingly wrote to the Times simply stating that “in justice to
the candidates for commissions in the artillery and engineers
examined by me in natural philosophy and chemistry, you will
perhaps permit me to state that the general level of the answers in
the last examination was much higher than that attained in the first;
many of the papers returned to me gave evidence of rare ability, and
if during their future career the authors of these papers continue to
cultivate the powers which they have shown themselves to possess,
they will, I doubt not, justify by their deeds the high opinion
entertained of them.” This modest statement, intended to put the
students right, put himself wrong. The Secretary of State for War
promptly informed him that an examiner appointed by the
Commander-in-Chief had no right to appear in the public papers as
Professor Tyndall had done without the sanction of the War Office.
To this reproof he at once wrote a firm but respectful reply, which,
however, he submitted to Faraday before despatching it. Faraday
pointed out that the consequence of sending such a reply would be
dismissal. Professor Tyndall said he knew that, but he would not
silently accept the reproof of the War Office. “Then send the reply,”
said Faraday; and it was sent. Henceforth Professor Tyndall was in
daily expectation of receiving his discharge. After a delay, the length
of which surprised him, he received a reply, the contents of which
still more surprised him. His explanation was “deemed perfectly
satisfactory” by the Secretary for War, and he therefore continued
for many years afterwards in the service of the Council for Military
Education.
One of the next subjects that occupied his attention was the
cleavage of slate rocks. It is a question of great importance in
connection with geological problems, and hitherto only speculative
solutions had been offered of what appeared to be one of the most
mysterious but grandest operations of nature. For twenty years
previously geologists were mostly content to accept on trust the
suggestion of Professor Sedgwick, that crystalline forces had
rearranged whole mountain masses so as to produce a beautiful
crystalline cleavage. In 1854 Professor Tyndall visited the quarries of
Cumberland and North Wales, where the question of cleavage came
prominently before him. When at Penrhyn Quarry he was told that
the planes of cleavage were the planes of stratification lifted up by
some convulsion into an almost vertical position. But a little
observation satisfied him that this view was essentially incorrect; for
in certain masses of slate in which the strata were distinctly marked,
the planes of cleavage were at a high angle to the planes of
stratification. A little experiment, he said, demonstrated that the
cleavage of slate was no more a crystalline cleavage than that of a
hayrick. An elaborate examination of all the conditions of the
phenomena led him to the conclusion that cleavage was the result of
pressure, and that this effect of pressure was not confined to slates.
In a lecture delivered in 1856 he stated that for the previous twelve
months the subject had presented itself to him almost daily under
one aspect or another. “I have never,” he said, “eaten a biscuit
during this period in which an intellectual joy has not been
superadded to the more sensual pleasure, for I have remarked in all
such cases cleavage developed in the mass by the rolling-pin of the
pastrycook or confectioner. I have only to break these cakes and to
look at the fracture to see the laminated structure of the mass.” He
exhibited some puff-paste baked under his own superintendence,
and explained that while the cleavage of our hills was accidental, in
the pastry it was intentional.
Among those who heard the lecture upon slaty cleavage was his
friend Professor Huxley, who suggested that probably the principles
then enunciated might account for the structure of glaciers, another
subject that had long perplexed scientific observers. The greatest
authority on glaciers at that time was Professor J. D. Forbes, of
Edinburgh University, who in 1842 declared that a “glacier is an
imperfect fluid or viscous body, which is urged down slopes of a
certain inclination by the mutual pressure of its parts,” and who
detected in glaciers a veined structure which he explained as fissures
produced by particles of ice in motion sliding past each other, leaving
the fissures to be filled with water and to be frozen in winter. On
examining the published observations of Forbes, Professor Tyndall
was struck with the probable accuracy of Professor Huxley’s
suggestion, and in order to examine the matter more thoroughly, the
two advocates of the cleavage theory arranged to visit together the
glaciers of Grindelwald, the Aar, and the Rhone. This personal
investigation and subsequent reflection confirmed Professor Tyndall
in his views. He found that glaciers were formed by the property of
ice which Faraday called regelation; that is, the freezing together of
two pieces of ice by simple contact and slight pressure. It is the
same property that enables boys to make snowballs and snow men
when the snow is beginning to melt, or when the warmth of the
hand raises its temperature to the point at which regelation takes
place. Professor Tyndall found that when two confluent glaciers
united to form a single trunk, their mutual pressure developed the
veined structure in a striking degree along their line of junction. In
his lectures on the subject at the Royal Institution he ingeniously
illustrated the processes of Nature which make and unmake the
glacier. To show that ice only becomes compressed into a solid mass
at a temperature near that of freezing water, he cooled a mass of ice
by exposing it to the action of the coldest freezing mixture then
known. He then crushed this cooled mass of ice into fragments, and
applied pressure to the fragments for the purpose of making them
cohere, but they did not show the slightest cohesiveness. Very
different was their action when their temperature was raised to the
freezing point. When placed in a wooden cup and pressed by a
hollow wooden die a size smaller than the cup, the pieces of ice
became united into a compact cup of nearly transparent ice.
Glaciers, he contended, were formed by a similar operation. As
particles of snow or ice descend the mountain side, the pressure
becomes sufficiently great to compress the particles into a mass of
solid ice, which eventually assumes the magnitude of a beautiful
glacier. He observed that in the laboratory of Nature it was exactly at
the places where squeezing took place that the cleavage of the ice
was most highly developed. In fact, he said, the association of
pressure and lamination was far more distinct in the case of the
glacier than in the case of the slate rock, and as it was now known
that pressure caused the lamination of slate rock, he contended that
it was the same cause that produced like effects in glaciers.
In a lecture delivered early in 1858, he gave an account of some
beautiful phenomena of the glacier. In the preceding September and
October he examined the effect of sending a beam of radiant heat
through a mass of ice. When sunbeams condensed by a lens were
sent through slabs of ice, the path of the beam was instantly
studded with lustrous spots like brilliant stars, and “around each the
ice was so liquefied as to form a beautiful flower-shaped figure,
possessing six petals. From this number there was no deviation. At
first the edges of the liquid leaves were clearly defined: but a
continuance of the action usually caused the edges to become
serrated like those of ferns. When the ice was caused to move
across the beam, or the reverse, the sudden generation and
crowding together of these liquid flowers, with their central spots
shining with more than metallic brilliancy, was exceedingly beautiful.”
By means of the electric light and a piece of ice prepared for the
purpose he was able to exhibit these lovely ice-flowers to a delighted
audience at the Royal Institution.
During the years 1857 and 1858 Professor Tyndall continued his
observations of glacier phenomena amid the solitude of the Alps. In
the summer of the latter year he betook himself to the mountains
with the view of settling once for all “the rival claims of the only two
theories, which then deserved serious attention, namely, those of
pressure and of stratification.” Again his former views were
completely confirmed. It is difficult, he said, to convey in words the
force of the evidence which the glacier of Grindelwald presents to
the mind of the observer who sees it; it looked like a grand
laboratory experiment made by Nature herself with special reference
to the point in question. The squeezing of the mass, its yielding to
the force brought to bear upon it, its wrinkling and scaling off, and
the appearance of the veins at the exact point where the pressure
began to manifest itself, left no doubt on his mind that pressure and
structure stood to each other in the relation of cause and effect.
The conclusions at which he arrived as to the structure and
movement of glaciers brought him into collision with Professor
Forbes, whose views, enunciated fifteen years previously, were then
widely accepted as the most scientific exposition of the subject.
Forbes seemed rather sensitive about his own theory, and
complained that he had to some extent been misrepresented. But in
the conflict of opinions Professor Tyndall invariably referred to
Professor Forbes’s labours in connection with the subject in the most
appreciative and complimentary language. For instance, in 1858 he
said he would not content himself with saying that the book of
Professor Forbes was the best that had been written upon the
subject; “the qualities of mind, and the physical culture invested in
that excellent work, were such as to make it, in the estimation of the
physical investigator at least, outweigh all other books upon the
subject taken together.” That is more generous language than
Professor Forbes ever used respecting Professor Tyndall. In 1865,
after the heat of controversy had been dissipated, Forbes wrote that
“Dr. Tyndall’s so-called proofs that it is through ‘fracture and
regelation’ that a glacier moulds itself to its bed are to my mind no
proofs at all;” and that he regarded Mr. Hopkins’s mathematical
demonstrations about glaciers as “irrelevant mathematical
exercitations.” Nevertheless, Professor Tait, the friend and scientific
biographer of Forbes, said in 1873: “To say that Forbes thoroughly
explained the behaviour of glaciers would be an exaggeration; but
he must be allowed the great credit of being the Copernicus or
Kepler of this science.” As the subject still continues to exercise the
intellect of the scientific explorers of the Alps, suffice it for the
present to say that if time ratifies the position which Professor Tait
has assigned to Professor Forbes, his greatest and boldest successor
in the same field may be described as the Newton of glacier
phenomena.

FOOTNOTES:
[2] The force of diamagnetism is vastly feebler than that of
ordinary magnetism. According to Weber, the magnetism of a thin
bar of iron exceeds the diamagnetism of an equal mass of
bismuth about two and a-half million times.
CHAPTER III.
“Every secret which is disclosed, every discovery which is
made, every new effort which is brought to view, serves to
convince us of numberless more which remain concealed, and
which we had before no suspicion of.... Knowledge is not our
proper happiness. Whoever will in the least attend to the
thing will see that it is the gaining, not the having of it, which
is the entertainment of the mind.”—Bishop Butler.

Next, probably, to magnetism and electricity, the scientific


investigation of the laws of heat has yielded the most fruitful and the
most curious results. The science of heat made the greatest
progress about the middle of the present century, and Professor
Tyndall was one of its most successful investigators. Being a force
co-related to electricity, it is scarcely remarkable that the same
natural philosopher should reveal to us not a few of these silent
operations of magnetism and heat that previously were unobserved
or were regarded as mysteries.
When, in 1859, he turned his attention to the absorption of
radiant heat by gases and vapours, there was considerable diversity
of opinion as to the effect of the atmosphere on radiant heat; and
great skill and patience were required in devising experiments, and
in detecting and eliminating the various sources of error. Till then it
was thought that the subject was outside the realm of experiment,
but Professor Tyndall soon demonstrated that heat in gases and
vapours was subject to various laws which had most important
effects in every part of the world. In his first memoir he established
not only the existence of absorption and radiation in gases, but that
the differences of absorption and radiation were as great among
gases as among liquids and solids. He showed that the elementary
gases, hydrogen, oxygen, nitrogen, as well as air freed from
moisture and carbonic acid, examined in a length of four feet,
absorb about 3½ per cent. of heat radiated from lamp-black at
212°, the slightest impurity in the gas, however, altering the rate of
absorption. With compound gases and vapours very different results
were obtained. About twenty gases and vapours were examined,
and it was found that while the elementary gases already named
gave the feeblest action, olephiant gas showed the most energetic
action, absorbing 81 per cent. He also made the important discovery
that by arranging the various gases in order according to their
power, first of radiating heat and then of absorbing radiant heat, the
order was the same in both cases; in short, the order of radiation
was exactly that of absorption. In his second memoir he introduced
a new and remarkable method of determining absorption and
radiation. This method he called “dynamic radiation.” Dispensing
with the use of any extraneous source of heat, he obtained his
results by the heat or cold produced by the condensation or
rarefication of the gases. Just as a ball striking a target is heated by
collision, so he heated gas contained in one part of a tube by the
collision of its particles against the surface of another part into which
they rushed to fill a vacuum. He found, he said, by strict
experiments that the dynamic radiation of an amount of boracic
ether vapour, possessing a tension of only one 1,012,500,000th of
an atmosphere, was easily measurable.
His researches on the relation of radiant heat to aqueous vapour,
published in 1863, were the most interesting and useful. Such were
the difficulties connected with the investigation of this part of the
subject that Professor Tyndall and his old friend Professor Magnus,
of Berlin, arrived at and long maintained opposite conclusions as to
the absorption of radiant heat by the air and the influence of
aqueous vapour. Early in his researches Professor Tyndall regarded
the action of the atmosphere as a particular part of his inquiry, and,
accordingly, his third memoir was specially devoted to the radiation
of aqueous vapour. The conclusion he came to was that the aqueous
vapour in our atmosphere intercepted or absorbed eighty times more
heat than the air, and as there was only one atom of aqueous
vapour for every 200 of oxygen and nitrogen composing the air, it
appeared that one atom of the former absorbed 16,000 times more
than one atom of oxygen or nitrogen. This startling conclusion he
verified by a system of checks and counter-checks which were
considered as decisive. The applications of this discovery were
manifold and important. The aqueous vapour which absorbed so
much heat he likened to a blanket which is more necessary to the
vegetable life of England than clothing is to man. “Remove for a
single summer night,” he said, “the aqueous vapour from the air
which overspreads this country, and you would assuredly destroy
every plant capable of being destroyed by a freezing temperature.
The warmth of our fields and gardens would pour itself unrequited
into space, and the sun would rise upon an island held fast in the
iron grip of frost.” The aqueous vapour constitutes a local dam,
which deepens the temperature at the earth’s surface, but which
finally overflows and gives to space all that we receive from the sun.
This discovery presented an explanation of some phenomena, which
hitherto had been imperfectly understood. It was evidently the
absence of this aqueous screen which made the winters in Central
Asia almost unendurable; and it showed how the burning heat of the
Sahara during the day was followed by intense cold at night.
Before Professor Tyndall had published all his observations on the
relations between radiant heat and aqueous vapour, his friend,
Professor Frankland, regarded them as sufficient to account for the
glacial era, and the action of glaciers over the entire globe. During a
visit to Norway in 1863 Frankland considered the subject afresh, and
came to the conclusion that the chief cause of the phenomena of the
glacial epoch was a higher temperature of the ocean than prevails at
present. The critics of the day pointed out that such a view
depended upon the accuracy of the assumption that our earth had
gradually cooled down from an originally incandescent state; and it
is now generally admitted by natural philosophers that the earth has
cooled down from a state of liquid heat. In that case the waters of
the ocean, when cooling down from the boiling point, would be at a
higher temperature than the present; and Professor Frankland
maintained that it was in the later stages of the cooling process that
the glacial epoch occurred. The great natural glacial apparatus he
divided into three parts—the evaporator, the condenser, and the
receiver. The cooling ocean was the evaporator; the mountains were
the icebearers or receivers; while the dry air which permitted the
heat from the vapour to radiate into space, acted as the condenser.
He made numerous experiments to show that under these
conditions the land would cool more rapidly than the sea; and he
maintained that in the glacial epoch the “rays of heat streamed into
space from the ice-bearing surfaces with comparatively little
interruption, whilst the radiation from the sea was as effectually
retarded as if the latter had been protected with a thick envelope of
non-conducting material. Thus, whilst the ocean retained a
temperature considerably higher than at present, the icebearers had
undergone a considerably greater refrigeration.” He calculated that
an increase of 20° in the temperature of the coast of Norway would
double the evaporation from a given surface, and such an increased
evaporation, accompanied of course by a corresponding
precipitation, “would suffice to supply the higher portions of the land
with that gigantic ice-burden which ground down the mountain
slopes during the glacial epoch.” Such a view did not require the
assumption of any natural convulsion or catastrophe; on the contrary
it accounted for the glacial epoch by the evolution of thermal
conditions, the existence of which is now generally admitted.[3]
In his fourth memoir, published in 1864, “On the Radiation and
Absorption of Heat by Gaseous and Liquid Matter,” Professor Tyndall
showed that generally the absorption of non-luminous radiant heat
by vapours was the same as that of the liquids from which the
vapours were produced.
His fifth memoir, entitled “Contributions to Molecular Physics,” was
made the Bakerian lecture for that year. In it he deduced from
numerous experiments the remarkable law that the opacity of a
substance with respect to radiant heat from a source of
comparatively low temperature increases with the chemical
complexity of its molecule. He examined the effects of temperature
on the transmission of radiant heat, the radiation from flames of
various kinds, and the influence of vibrating periods on the
absorption of radiant heat.
In November, 1864, the Royal Society presented him with the
Rumford medal for his researches on the absorption and radiation of
heat by gases and vapours; and General Sabine, in making the
presentation, said such had been the fate of Professor Tyndall that
each last achievement might almost be said to have dimmed the
lustre of those which preceded it. Curiously enough his very next
achievements thereafter did dim the lustre of those published prior
to the presentation of the Rumford Medal. It was the discovery of a
means of separating light from heat. Melloni had previously
discovered a combination of screens by which radiant heat could be
arrested or separated from light, an operation which is effected on a
vast scale by the moon when it reflects the light of the sun.
Professor Tyndall effected the converse operation. He discovered
that a solution of iodine in bisulphide of carbon entirely intercepted
the light of the most brilliant flames. A hollow prism filled with that
opaque liquid and placed in the path of the beam from an electric
lamp, completely intercepted the light, but transmitted the heat
unimpaired. In this way he succeeded in separating with marvellous
sharpness the invisible from the visible radiations of the lime light,
the electric light, and the sun. He not only produced combustion,
fusion, and incandescence by invisible radiation, but he proved that
in the case of the electric light the invisible rays are no less than
eight times as powerful as the visible radiations. He obtained all the
colours of the solar spectrum from a platinum foil raised to
incandescence at the invisible focus; and this rendering of a
refractory body incandescent by invisible rays he called calorescence.
In connection with these investigations he performed a daring
experiment. Knowing that a layer of iodine placed before the eye
intercepted the light, he determined to place his own eye in the
focus of strong invisible rays. He knew that if in doing so the dark
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookgate.com

You might also like