Complete Download Interactive Data Visualization for the Web 1st Edition Scott Murray PDF All Chapters
Complete Download Interactive Data Visualization for the Web 1st Edition Scott Murray PDF All Chapters
https://ebookgate.com/product/learning-ipython-for-interactive-
computing-and-data-visualization-2nd-edition-cyrille-rossant/
ebookgate.com
https://ebookgate.com/product/everyday-data-visualization-desiree-
abbott/
ebookgate.com
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
https://ebookgate.com/product/handbook-of-statistics-24-data-mining-
and-data-visualization-c-r-rao/
ebookgate.com
https://ebookgate.com/product/social-data-visualization-with-
html5-and-javascript-timms/
ebookgate.com
https://ebookgate.com/product/html5-graphing-and-data-visualization-
cookbook-1st-edition-ben-fhala/
ebookgate.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
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
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
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
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Download from Wow! eBook <www.wowebook.com>
ix
On visual design principles and techniques:
• 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.
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.
Preface | xi
How to Contact Us
Please address comments and questions concerning this book to the publisher:
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
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 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.
• 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.
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.
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
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:
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:
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.)
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.
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.
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:
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.
• fevers
• chills
• general malaise
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
Headline
Paragraph text
Paragraph text
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>
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.
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.
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:
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).
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>
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.)
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?)
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.
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.
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.
ebookgate.com