0% found this document useful (0 votes)
27 views25 pages

Adobe Scan Jun 22, 2023

Uploaded by

alekhyahema12
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
0% found this document useful (0 votes)
27 views25 pages

Adobe Scan Jun 22, 2023

Uploaded by

alekhyahema12
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/ 25

CaPTERi An N0roducthon

sophisticateddata visualiza-
web-accessible, they
ned tor tools for a while, but
WhatisD3Js? pressing BusinCss Intelligence necds. You need
to
tilla used your team
craleltocompan has the data that customers are behaving, tai-
L1 pattens in interacti
Dasws sn OUr of showsexactly
how your fast.
Inn Let s the kind needs to be
sboN 0 dashboardthat dsnoOaTa that
use D3for
n't cUsKom domain. That goingto take advantage of emerging
buukda vor syific You
organization. re to
created D3 representation and affords
lovedfo originally
aroundthe Bostock, proprietary standards such as CSss,
shareable Mike "avoids
capabilities of webiteration of this popular
s
crrator, he putsit.
DSjs as full
standards, which, exposingthe veersion4,thelatest D3 to make it more
web flexibility, D3.js various pieces of
exiraordinary (http://d3js.ong). modularizingthe
SVG" animated con-
HIML5,and this rend by development. interactive and
continues rich
librar,
modem
application ability tocreate elements. It gives you the
usefulin the
developes withcontent tto existing web pagesophisticated data visualiza-
and
D8providesdata and ticthat data dashboards
tent basedon high-performance content.
raditionalweb andfound that it isn't easy to get
create
tools to dynamicallyupdate experimented with D3 charting library. A case in
tion,and to simple
might have already expected itto be a 5.
have one single
D3 doesn't dataset
You you chapter with
Maybe that'sbecause whichyou1'llsee in processes your
into. chart layout, Rather,it has a function that arcfunction, you get the
pointis the pie
pie chart. to D3's another
funcion tocreatea you pass the dataset need to use yet
angles so that if
angles. And you than
the necessary necessary to represent those much longer process
drawing code necessary for that code. It's a which D3 deals with
paths manner in
function lo create the libraries, but the explicit libraries conveniently
singdedicated
charting
strength. Although other charting
break down when vou
want
is also its quickly
data and graphics line graphs and pie charts, they allows you to build whatever
allow vou tomake different than that. Not D3, which
something
to make
and interactivity you can imagine.
data-driven graphics

12 How D3 works as well as how D3 works in general. In


data visualization,
Lets look at the principles of how you might start with data and use D3 to process
figure 1.1 you see a rough map of interactivity and optimize the data visualization
as add
and representthat data, as well start by establishing the principles of how D3
vou've created. In this chapter, we'll HTML
and data-binding work and learning how D3 interacts with SVG and
selections
that you'l commonly encounter. Finally,
in the DOM Then we'll look at data types elements.
well use D3to create simple DOM and SVG
121 Data visuallzatlon is more than charts
You may think of datavisualization as limited to pie charts, line charts, and the variety
of charting methods popularized by Edward Tufte and deployed in research. It's
much more than that. One of the core strengths of D3.js is that it allows for the
5
How D3 uorks

Data Load data


32101011 (chapters 2 and 3)
00011101
11011010
J101010i
101101i01 Process data
10101111 (chapter 2)

Generate Bind data


adataset
(chapter 2)
(chapter 11)

Charts

Design Basic Hierarchical Networks Maps


(chapter 3) charting layouts (chapter 7) (chapter 8)
(chapters 2-5) (chapter 6)

Interactivity basics
(chapter 2)

Interactivity

MVC dashboard Extending D3


Mouse events Brush filtering
(chapters 9 and 11) (chapter 9) (chapter 10)
(chapters 2-12)

Zoom
(chapters 5 and 7) Optimization
(chapter 11)

Flgure 1.1 Amap of how to approach data visuallzation with D3.<s that highlights the approach in this
book. Start at the top wth data and then follow the path depending on the type of data and the needs
you're addressing.

creation of vector graphics for traditional charting, but also the creation of geospatial
and network visualizations, as well as rich animation and interactivity. This broad
based approach to data vistualization, where amap or a network graph or a table is
another kind of representation of data, is the core of the D3,js library's appeal for
application development.
intrvductionto D3,js
OAPTER1 An

l2 through Isshow
Figures thatI've
visualizationpieres inlude
ciata Ther
cTeated ith D3. along with
naps and neworks, and
traditional pie charts Flgure 1.2 D3 can be
IRore data visual used for simple charts,
completely customn such as this donut
based on the spe Chart
(explained In chapter 5).
ization laouts
clients.
cific needs of my

Figure 1.3 D3 can also be


used to create web maps (see
chapter 8), such as this map
showing the ethnic makeup of
major metropolitan areas in the
United States.

Figure 1.4 Maps in D3 aren't limited to


traditional Mercator web maps. They can be
interactive globes, like this map of undersea
communication cables, or other, more
unorthodox maps (see chapter 8).
7
How Dì uorks

Figure 1.5 D3 also provldes robust


capacitles tocreate interactlve
network visuallzatlons (see chapter 7).
Here you see the soclal and
coauthorship network of
archaeologists working at the same
dig for nearly 25 years.

O ccounts but that

O Bdvance search used to be better Oreferences elsewhere in scholarship on and off the web to find titles

O digitized collecúons such as -url

O where they take me

Google O

O googie ngrams

O is hard to use

Odatabase, I don't get good access to this type of naterial

BookO
O project bad proceeded -or sone sumlar mechanism for digitizing all books

OScan alt textbooks and older seience books and make available on the web

Flgure 1.6 D3includes a library of common data visuallzatlon layouts, such as the dendrogram (explained in
chapter 6), that let you represent data, such as this word tree.
you can create your own
drawing functions(see chapter 4): so
SVGand canvas musical scores.
Fgure 1.7 D3has such as this representation of
custom visualzatlons,

04PM 08PM
08AM 12PM
we'll
and functlons to create a data dashboard like
Aigure 1.8 You can combine these layouts
functlons to make your bar charts look distinctive.
do in chapter 9. You can alsouse the drawng
such as this "sketchy style.

strong points,
Although the abiliy to Create rich and varied graphics is one of D3's
embed the high levelof
more important for modern weh development is the ability to
interactivity that users expect. With D3,every element of every chart, from a spinning
globe to a single, thin slice of a pie chart, is made interactive in the same way. And
because D3 was written by someone well versed in data visualization practice, it
EGINEFRLNg
UBRARY
EFERENCE ONLY
lHow D³works NOT FOR ISSUF
data visualization
indudes in ce components and behaviors that are standard in
and webopnent.
RrALM Ptootontinvest Vour tinie learning D3 so that vou can deploy Excel-style charts on
ror that, easier, more convenient libraries exist. You
learn D3 because it gives
technique. It also
you the ablity to implement almos every major data visualization
something a
gves you the power to create your own data visualization techniques,
D3, look
Inore general library can't do. To see the variety of possibilities available with
at htup:// blockbuilder.org/search.
DSJs aftords developers the capacity to make not only richly interactive applica
like traditional web content.
hOns but also applicaions that are stvled and served
growing, linked data web,
Ihis makes them more portable, more amenable to the
other team members don't know
and more easily maintained by large teanms where
053262
the specitic synax of D3 but, for instance, can use CSS to
style the data visualization
22B elements.
data and to create a library
The decision on Bostock's part to deal broadly with
005
No. easily as networks, as easily as
Call capabie of presenting maps as easily as charts, as to understand the
ordered lists, also means that a developer doesn't need to try
dynamic text content,
absractionsand syntax of one library for maps,and another for force
running an interactive,
and another for datavisualization. Instead, the code for
similar to the code repre
directed network layout is close to pure JavaScript and also
map. Not only are the methods
sening dynamic points of interest (POls) on a D3,js
formulated in one way for lists and
the sane, but he data also could be the same,
geospatial representation.
paragraphs and spans, while formulated in another way for
L2.2 D3 Is about selecting and binding
can run in your browser to
Throughout this chapter, you'll see code snippets that you
elementson your website. At the end of
make changes to thegraphical appearance of the code we're
explains the basics of
the chapter is an application written in D3 that the principles of web develop
running ín JavaScript. But before that we'll explore and over again: selecting.
ment using D3, and you'llsee this pattern of code over size of a few houses, and a set
and
Imagine we have aset of data, such as the price
elements, and that we warnt to repre
of webpage elements, whether graphics or <div> of
the dataset, wheher with text or through size and color. A selection is the group
sent group,
on the elements in the
the data and elemnents together. We perforn actions
likewise update the values in the
such as mnoving then or changingtheir color. We can elements separately, the real
page
data. ThOugh we can work with the data and the web
combine data and web page elements.
power of D3 comes from using selections to
Here's a selection without any data:
("cx", 100) ;
d3.selectAli ("circle.a") .style ("fil] ", "red").attr
turns it red, and moves it so
This takes each circle onour page with the CSS class of a,
<svg> canvas. Likewise,
that its center is 100 pixels to the right of the leftside ol our
b:
this codeturns every div on ourweb page red andchanges its class to
ed atyClasst,

we' needto (reate rhem.,


Onles
anddivs,
inthis pattern: and bek
ca
hange OHI what's happeing
Ifore e
R

renderer.
D3 with React, a view
s selectingnecessary?
chapter 11 you'
Angular or view
to use
Typi
see howrendering libraries lIke React are responsible
associating them with certain
cally.
Laterin ike elements and update dat.
MVCHOraries destroying HTML stop using D3to create and elementsand
creating and cases, you might application.
foryour
points.tnthose visualizationkernel
asa
useitpurely
t
code,d3.selectAll(0),is part of the core functionality nec-
part ofthat line of Selections can be made with
The first understanding D3: selections.
essary for
the first single clement found, but more
Selections
d3.lectAll
select(),
often you'll use d3.sel
are groups of one Or
),
which selects elements. more
select multiple like the
which
web
can be uscd
page clements
to
that may be
associated with a set of data,
following code,
[1,5,11,3] to <div> elements with the class of
elementsin the array
which bindsthe
market:
([1, 5, 11,3])
d3.selectAli("div. market "). data 2e
D3 as binding data, and you can think of aselection
This association is known in corresponding, associated set of data. Sometimee
ofweb page elements and a elements, or vice versa, in which case D3 has functions
data elenments exist than DOM
use to generate content. Chanter
designed to create or remove elements that you can
Selections might not include anydato
2covers selections and data binding in deail.
chapter, but the inclusion allou
binding, and won'tfor most of the examples in this
can make a selection on
the powerful infonationvisualization techniques of D3. You
any elements in aweb page, including items in a list, Circles, or even regions on a man
of Africa. The sane way the elements can take a number of shapes, the data associated
with those elements (where applicable) can take many forms.

D3 is about derving the appearance of web page elements


from bound data
After vou have a selecion, youcan then use D3 to modify the appearance of web page
elemeuts o retlect differences in the data. You may want to make the length of a line
equal to the value of the data, or change the color to one that corresponds to a class of
data You may want to hide or show elements as they
of a dataset. As you can see in figure 1.9, correspond to a user's navigation
after the page has loaded, you use D3 to
select elements and bind data for creating,
removing, or changing DOM elements. You
continue to use this process in response to user
interaction.
The power of HTML5

I. Page loads with styles, data,


and content as defined in
traditional HTML development.
(This step only happens once.)
3. Changes in page structure
prompt user interaction, which 2. Display uses D3 selections
causes new selections with and of HTML elements, with or
without data-binding to further without data-binding, to
alter the page (multiple times, Load web page modify the structure and
depending on user interaction). appearance of the page.

Select elements

User interaction Bind data

Create/update/remove elements

Figure 1.9 An application created with D3 can use selectlons and data binding over and over again,
together and separately, to update the content of the data visuallzation based on interactlon.

You modify the appearance of elements by using selections to reference the data
bound toan element inaselection. D3 iterates through the elements in your selection
and perfonns the same acion using the bound data, which results in different graphi
cal effects. Although the action you performn is the same, the effect is different
because it's based on the variation in the data. You'll see data binding first at the end
of thischapter, and in much more detail throughout this book.
12.4 Web page elements can now be divs, countries, and flowcharts
We've grown accustomed to thinking of web pages as consisting of text elements with
containers for pictures, videos, or embedded applications. But as you grow more
familiar with D3, you'll begin to recognize that every element on the page can be
reated with the same high-level abstrac tions. The most basic element on aweb page, a
caiv» that represents a rectangle into which you can drop paragraphs, lists, and
tabBes, can be selected and modified in the same way you can select and modify a
country on a web map, or individual circles and lines that make up a complex data
visualization.

13 The power of HTML5


We've come a long way from the days when aninated GIFs and frames were the pinna
cde of dynanic content onthe web. Infigure 1.10, you can see why GIFs nevercaught
on for robust data visualization on the web. GIFs, like the infoviz libraries designed to
CHAP

Photorealistic 3D Graphlng Sofhware


Visuallzation
DPGPaph: Dynamie Matharnd
Physics
or Sec 2013
2ewasYRen
eUIN/R EiaszCacect
Labcsk p GgeYoDnl
tadt A
ter You be d
software for
most powerul
The wonid's visuaBzaion. Create
physiCS
math ard interactive, dynamic
beauliful,
70
4D, 5D, 60D, even
photorealistic 2D, 3), use that
So easy to
and 8D graphs senior high students have
junior hgh and includes
graphs pubiished
had their examples contributed by
hundreds of the world
around
Users from
mathematicians,
Over wO million and students at
over
ptysicists, teachers
universities and K-12
1,000 colieges, are already licensed.
schools worldwide subscription to the
Comes with a free
ElamingThunder prograrnming
language
search
DPGraph using both yourfavorite and
search for classroom
internet- DPGraph for
Optimized for the thet people are usinggeometry, trigonometry and general and
engine to find waysUsed for pre-algebra, quantum mechanics
distance feaming.multivaniable calcukus, ffeld theory,
physics, through
gravitation. motion or encode
(to create parameters in realtime, to
color as extra dimensions
scrolbar to varv
Use time and Use the
monenthum, for example).
they were your only
animal behavior, dpgraph.com hope for
weaponized to share cute still exis
like
Flgure 1.10 Before
GIFs were
web. Few examplesfrom the 1990s
on the dangers.
animated deta visuallzation GIFs to remind us
of thelr
than enough
this page has more
but D3 is designed for the modere
browsers,
necessary for carlier
use VML, were backwardcompatibility.
browsers thatno longer need
foundational to understanding D3.js, but if you're
NOTE SVG knowledge is this section to
DOM,SVG,and CSS, youcan skim
alreadyexperienced with the ahead to section 1.3.6 or l.4.
skip
refresh vour menory, or
only display SVG graphics and obey CSS3 rules, but
can not
Amodern browser typically Along with Cascading Style Sheets (CSs) and Scalable
also has great performance.other elements you need to know about for web develop
VectorGraphics (SVG),the Model) and JavaScript. The following sections
ment are the DOM (Document Object their
incude code you can run tosee how D3uses
dealwith each of thembroadly and
web content.
functionalirytocreate interactive and dynamic
L3.1 The DOM
You need a passing familiarity with
A web page is structured according to the DOM. quick look at DOM elements and
the DOM to do web development, so we'll take a basics of the DOM.
on the
structure in asinple web page in your browser and touch
that
To get started, you'll need a weh server that you can access from the computer
you're using to code. With that in place, you can download the D3 library from
d3js.org (d3 js or d3.minjs for the minified version) and place that in the directory
13
The power of HTML5

where you llmake yourweb page.You'll create a page called d3ia.htunlin the text edi
torwith the contents in the following listing.
Listing 1.1 Asimple web pate demonstrating the DOM
<!doctype htmì>
<htmì>
<head>
<sCript src- "d3.v4.min.js"></sript>
</head> A
child element of <html>
<body>
sáiv id="gomeDiv" stylez "width :20Opx; height :100px; border :black ipx sol id; ">
<nput id="s omeCheckbox" type-" checkbox* /> Achild element
</áiv>
A
child element
of <div> of <body>
</body>
</html>

Basic HTML like this follows the DOM. It defines a set of nested elements, starting with
an <html> clement with all its child elements and their child elements and so on. In
this example,the <script> and cbody> clements are children of the <html> element,
andthe <div> element is a child of the <body> element. The <script> element loads
the D3library here, or it can have inline JavaScript code, whereas any content in the
<body> element shows up onscreen when you navigate to this page.
Three categories of information about each element determine its behavior and
appearance: styles, aturibues, and properties. Sryles can determine transparency, color,
size, borders, and so on. Atributes include classes, IDs, and interactive behavior,
thoughcertain atuributes can also determine appearance, depending on which type of
element you're dealing with. Properties typically refer to states, such as the "checked"
property of a check box, which is true if the box is checked and false if the box is
unchecked. D3 has three corresponding funcions to modify these values. If we
wanted tomodify the HTML elements in the previous example, we could use D3 func
tions that abstract this process:
d3. select("#someDiv") .style("border", "5px darkgray dashed");
d3.select{" #S omeDiv") .attr("id', "newID");
d3.sel eut("#s OmeCheckbox" ) .property("checked", true) ;
Like many D3 functions of this kind, if you do't signify a new value, then the funcion
Ietums the existing value. This way of exposing getter/setter behavior in JavaScript
was popularized in JQuery and shows up in most of the D3examples. You'llsee this in
a tion throughout this book, and later in the chaper as you write more code, but for
wJemember that these three funcions allow you to change how an element
appars and interats.
The DOMalv) deternines the onsCreen drawing order of elements, with child ele
ments drawn after andinside parentlements. Although you have parialconrol over
drawing clerneuts above or below each other with tradiional HIML using z index,
this won' t be available with SVG elenents untilthe svGZ spec is inplennented.
14 CHAPTER 1 An introduction to D3.js

Click for element inspector

Deveioper Tools http://127.0.0.11jd3_in.action


Memory Console Elements Sources Network 2/chaptPertormance
er 1/1.11.htrni
bedy
Vidtht 200px) ghtr 10Bpx
darkgray$ border Spx dashed
278-118 $oneChe ckbOx type checkbox

Pscrápt type text/j avascript /script


/body
fhtrl

htm body dhovwD


Styes Eent Listeners DOM Breakpoints Properties
FSer :hov .cls

maren
w1dtn! 200px;
he ight: 1e0px; border
bo rder: 5px dashed da rko ray: Caadding -
200 106
div { User agent sty lesheet
display: block:

Figure 1.11 The developer tools in Chrome place the JavaScript console onthe
labeled Console, with the element inspector available using the arrow in a rightmost tab.
on the top left or by browsing the DOM in the Elements tab.
rectangle (circled above)

EXAMINING THE DOM IN THE CONSOLE


Navigate to d3ia.html, and you can get exposure to how D3 works. The page isn't too
impressive, with only a single, black-outlined rectangle. You could modify the look
and feel of this web page by updating d3ia.html, but you'll find that
it'seasy to modify
the page by using your web browser's developer console. This is useful for testing
changes to classes or elements before implementing them in your code. Open the
developer console, and you'll have two useful screens, shown in figures 1.1l and 1.12,
which we'll go back to again and again.
Eemenss Network Sources Timeline Profiles Resources Audits
<Lop frame>
Preserve log
¬3.e ei"#si). style "background", " red" )
( Array 13} )

Console Starch Emulation Rendering

Figure 112 You can run Javascript code in the


new ones as necesary. Any code you wrte in the console and catl global variables or declare
are lost as soon as you reload the page. console and changes made to the web page
15
The pourr of HTML5
NOTE You'll see the console in this first chapter. but in
vou're familiar witlh it, I'll shOw only the output. chapter 2. one
The element inspector allows vou(o look attheelements that make up your web page
h naigatng through the DOM (represented as nested text, where each child cle
ment is shown indented). You can also select an clement onscreen graphically, typ
cally represented as a magnifying glass or cursor icon.
The other screen you'll want to use guite often is theconsole (figure 112), which
allows you to write and run JavaScript code right on your web page. The developer
tools have other valuable features, such as setting breakpoints and the abiity to
inspect network calls, buu we're going to focus on using the console to change cle
ments and run code.
The examples in this book use Google Chrome and its developer console, but you
could use Salari's or Firefox's developer tools with the same functionality and slightly
different look-and-feel, or use your code editor and refresh the page. You can see and
manipulate DOM elements such as <div> or <body> by clicking the element inspector
or looking at the DOM as represented in HTML. You can click one of these elements
and change its appearance by modifying it in the console.
Youcan even delete elements in the console. Give it a tury: select the div either in
the DOM or visually and pres Delete. Now your web page is lonely. Press Refresh so
vour page reloads the HTML and your div comes back. You can adjust the size and
color of your div by adding new styles or changing the exising one, so you carn
increase the widh of the border and make it dashed by changing the border style to
Black 5px Dashed. You can add content to the div in the form of other elements, or
you can add text by right-clicking on the element and selecting Edit as HTML, as
shown in figures 1.13 and 1.J4.

Developer Tools -http://


Elements) Network Sources Timeline Prof
F<htn data-enber-ext ens L0n1">
chead><fhead

Vsneiv 242ex 1420x height Add Attribute


bluck Edit Attribute
<fbody>
</html>
Force Element State

Edit as HTML
Copy C5S Path
Copy XPath
Copy
Cut

Delete Node

nts body Scroll into View


Consoie Sei
Break on

Figure 1.13 Rather than adding or moditying individual styles and attributes, you
can rewrte the HTML Code as you would in atext edtor. As with any changes,these
only last until you reload the page.
I6 CHAPTER 1 An introduetion to D3,js

Sty leswidth: 200px; he ight: 10@px; bo rder


:ipx solic black; Me re's some text to
Put into my die/d1v>

Figure 1.14 Changing the


content of a
element is as simple as adding DOM
text between
</body opening and ending brackets of the element the
</html>

You can then write whatever you like in between the opening and closing
Anv changes vou make, regardless of whether they're well structured or HTML.
reflected on the web page. In figure 1.15 you see the results of1 not, will be
which is rendered immediately on your page. modifying the HTML,
Here's some text to put into wDeveloper Tools - http://:
my dËv
Q0lements Network Sources Timeline Prof
<html data-ember-extens ion="1">
ºchead>-.</head>
V <body>
<div 1d-someDiv" style="width:200px;
height: 100px; border:1px solid
black; ">Here's some text to put into my
div</div>
</body>
</htm l>

htm! body div#someDiv


Console Search Emulation Rendering

Figure 1.15 The page is updated as soon as you finish making your changes.
Writing HTML manuaily in this way is only useful for planning how you might want to
dynamicaly update the content.

In thís way, you couldslowly and painstakingly create a web page in the console. We're
not going to do that. Instead, we'l use D3 to create elements on the fly with size, p0s0
tion, shape, and content based on our data.
L3.2 Coding In the console
You'll do most your coding in the IDE or text editor of your choice, butone of the grea
hings about weh development is that you can test JavaScript code changes by using
your console Iater you'll focus on writing lavaScript, but for now, to demonstrate how
the console works, copy the following code into your console and
press Enter:
17
The power of HTMLS
d}.select ('div ") . style("backaround, *1ightblue").style ("border ", sOl1d
black px*). html ("You have now dynamically changed the content of a web page
element);

You should see the cffect shown in figure 1.l6.

Developer Tools htp/127.0.0 1/d3 In_actan 2fchapter1/116.tmi


You have now dynamically Mernony Console Elements Sources Netwotk Perlormarce >

changed the content of a web top fto

page element d).selecti 6iv'). styie f"backgravn6 l1ghtblue.sty le("borde r", "ol Ld
black ipri.html(Fou have now dyna 1(al1y changed the content o o w
nt

º (greups: Artayf1), psrents: Array(1}}

Rgure
HTML
1.16 The D3 select syntax modifles style using the .style () function, and traditBonal
COntent using the .html () function.

You ll see a few more uses of uraditional HTML elements in this chapter, and then again
inchapter 3, but then you won't see traditional DOM elements again in great detail.
Youcan use D3 to create complex, data-driven spreadsheets and galleries using <div>,
<table>, and <select> elements, but that's not a common use case in the real world.
If all D3 could do was select HTML elements and change their style and content like
this,then it wouldn't bethat useful for data visualization. To do more, we have to move
away from traditional HTML and focus on a special type of element in the DOM: SVG.
L3.3 SVG

A major valueof HTML5 is the integrated support for Scalable Vector Graphics (SVG).
SVG allows for simple mathenmatical representation of images that scale and are
amenable toanimation and interaction. Part of the attractiveness of D3 is that it pro
vides an abstraction layer for drawing SVG, because SVG drawing can be a little confus
ing. svG drawing instructions for complex shapes, known as <path> elements, are
wriuen a bit like the old LOGOprogramming language. You start at a point on a can
vas and draw a line from that point to another. If you want it to curve, you can give the
SVG drawing code coordinates on which to make that curve. If you want to draw the
line on the left, you'd create a <path> element in an <svg> canvas element in your
web page, and all those drawing instruc tions (that's what they look like on the left of
figure 1.17) go into the d attribute of that <path> element.

m 25.447534,104.50879 c 35.89856,7.45849 74.730166,45.01366


108.57 1426,11.42857 28.09984,-27.887135 47.81916,-92.985425
111.42857,-74.285715 31.98127,9.40176 26.13586,71.972865
62.85714,71 428565 55.39866,-0.82115 101.36764,-112 52070547
160,-45 714275 44.69105,50.921525 55.38932,45.730385
91.42858,37 142865

Figure 1.17 The commands to draw an SvG path (git) and the resulting graphic (left)
I8 CHAPTER 1 An introduction to D3.js

But you'd almost never want to create SVG by mnanually


writing
like this. Instead, you'll want to use D3to do the drawing with a drawingof
tions, or rely on other SVG clements that represent simple variety
shapes
ric or graphical primitives) using more readable attributes. You'll (known
chapter 4, where you'll use d3.svg.line and start
as
doing
ihelnstprerugeome-
ciofunc-n,
d3 .svg. area to create
charts. For now, vou'll update dSia.html to look like the line and areain that
incudes the necessar code for displaying SVG, as well as examples offollowing listing,
the which
shapes vou might use. vanous
Lsing L2 Asample web page with SvG elements
<!doctype html>
<htmi>
<script sr= "d3.v4.min.js">
<script>
<body>
<div id- "infovi zDiv">
<svg style- "width: 500px; height:500px; border:lpx lightgray solid;
<path d= *M 10, 60 40, 30 50,50 60, 30 70,80"
style= "fill:black; stroke :gray;stroke-width: 4px; " />
<polygon style-"fill:gray:"
points= "80, 400 120, 400 160, 440 120,480 60,460" />
<g>
<line xi="200" yl="100" x2 ="450" y2="225 "
style= "stroke: black;stroke-width: 2px; "/>
<circle cy-"100" cx="200" r="30" />
<rect x="410 y="200" width="100" height="50 "
style- "fill :pink; stroke : black;stroke-width: lpx; " />
<g>
<eVg>
</aív>
<,/boay>
<htn1 >

You can inspectthe elements like you would theraditional elements we looked at ear
lier, as vOucan see in figure 1.18, and youcan manipulate these elements using tradi
tional JavaScript selectors like ocumen t .getEl ement By Id or with D3, removing then
orchanging thestyle like s0.
G3. gei ect circle').removet ) Deletes the circle
d2.select ('rect) etyie (" fil2 ", "purple") + Changes the rectangle color to purple

Now reresh your page and let's look at the new elements. You're familiar with divs,
and ir's usecful to put ansVG canvas in a div so you can access the parent containerlor
layout and styling. Let'slook at each of the elements we've added.
<svO> cONTAINER
This is your canvas on which everything is drawn. The top-left corner is 0,0, and the an
vas lips aything drawn beyond its defined height and width of 500,500(the recang'
in our exaiple). An <svg> element an be styled with CSS to have difterent borders alri
The power of HTML5 19

Q DElements Network Sources Timeline


V <htal data-enbe r -extens 1on1">
chead></head>
b0dy
T <div 1d="vizcontainer">
T<Svg>
<path d="M 18,60 40,30 50,50
60,30 70, 80" style="fill:black;
stroke:gray; st roke-width:
4px;"></path>
<polygon style="fill:gray; "
points="80,400 120,400 16e,440
128,480 60,460"></polygon>
<g></g>
</svg>
</div>
<footer>,</ footer>
</body>
</html>

html body
'svg 502us 502px ConsoleSearch Emulation Rendering

Figure 1.18 Inspecting the DOM of a web page with an SVG canvas reveals the nested graphical
elements as well as the style and attributes that determlne thelr positlon. Notice that the circle and
rectangle exist as chlld elements of a group.

viewBox
backgrounds. The <svg> element can also be dynamically resized using the
here.
attribute, which is more conplex and beyond the scope of the overview
style your SVG can
Youcan use CSS (which we'l touch on later in this chapter) to
this:
vas or use D3 to add inline stvles like
Infoviz is always cooler
"darkgray") ;
on a dark background
d3.select("svg"). style ("background
y-axis is drawn top-to-bottom,
NOTE The x-axis is drawn left to right, but the right and l100 pixels down.
to the
So you'll see that the ircle is set 200 pixels

<canvas> elements
available with HTML5 using <canvas>
There's a secondmode of drawing method used in
draw bitmaps. We won't go into detail here, but you' see this creates static
to pertormance. The <canvas> element
chapter 11 for its rendering SVG that can then be saved as images.
Here
graphics drawn in a manner similar to
use canvas:
are three main reasons to
canvas to
static images-YoU can draw your data visualization with
Creating
save views as snapshots for thumbnailand gallery views
CHAPTER 1 An introduction to D3.js

(continued)
Large amounts of data--SVG creates individual elements
in the
athough this is great for attaching events and styling, it can DOM, and
browser and cause significant slowdown (this is what we'll use
chapter 11). overwhelmfor ir.
canvas
WebGL--The <canvas> element allows you to use WebGL to draw, so
that
create 3D objects. You can also create 3D objects like globes and
polyhedronsyou carn
sVG, which we'l get into a bit in chapter 8 as we examine geospatial using
visualization.
informatior.
<CIRCLE>, <RECT>, <UNE>, <POLYGON> SHAPE PRIMITIVES
SVG provides a set of common shapes, each of which has attributes that
their size and posiuon to make them easier to deal with than the generic d determine
attribute
vou saw earlier. These attributes vary depending on the element you''re dealing
so that <rect> has x and y atributes that detemine the shape's topleft with.
corner, as
well as height and width attributes that detenine its overall form. In comnars
the <circle> element has cx and cy attributes that deermine the center of the c
cle, and an r aturnbute that detemines the radius of the circle. The <line> elemen.
has x1 and yl attributes that determine the staring point of the line and x2 and v:
atrnbutes that cdeternine its end point. Othersinple shapes are sinnilar to these, such
as the <eli ipse>, and other more con1plex shapes, like the <polygon> with a points
aturibute that holds aset of comma-separated xv coordinates, in clockwise order.
determine the area bounded by the polvgon

Infoviz tem: geometric primitive


Accompished artists can draw anything with vector graphics, but you' re probably not
tooking at D3 because you're an artist. Instead. you're dealing with graphics and have
more pragmatic goais inmind. From that perspective, it's important to understand
the concept of geometric primitives (also known as graphical primitives). Geometric
primitives are simple shapes such as points, lines, circies, and rectangles. These
shapes, wthich can be combined to make more complex graphics,are particularly use
fui for visualy displaying information.
Primitives are also useful for understand1ng compiex information visualizations that
yousee out in the real world. Dendrograms. ike the one shown in figure 1.20, are far
less intimidating when you reakze they're oniy circles and ines. interactive timelines
are easier to understand and create when youthink of thern as coliections of rectar
gies and points. Evern geographic data, which primariy comes in the fom of polygont
points, and lines, is less confusing when you break it down ito its most basic gra
ical structures.
21
The pouer of HTML5

49Bementsi Nerwork Sources Tmeline


Y<htel data-eebe r-extens ion"1">
head></head>

cdiv ide"vizcontainer'>
V<Svg>
<path d="M 10, 60 49,30 50,50
68,30 7e, 80" styles'"fill:black;
stroke :gray, stroke-width:
4px; "<loath>
<polygon style"fill:gray;"
pointsm"80, 400 120,408 160, 440
120,480 60,460"></polygon>
<Circle cy"100" or"20e r
rect 25Dx 25px "30></cárcle>
<rect x410 y200 widthw
"25" heightw"25" style"fiL
pink;stroke:black;strokevidth:
lpx;"</rect
</q>
</svg>
</div>
<footer>.</footer>
</body>
</html>

htm body div#vizcontainer svg g rect


Console Search Emulation Rendering

Figure 1.19 Moditying the helght and width attributes of a <rect> element changes the
appearance of that element. Inspecting the element also shows how the stroke adds to the
computed size of the element.

Each of these attributes can be hand-edited in HTML to adjust its size, formn, and posi
width to 25 and
tion. Open your element inspector and click the <rect>, Change its
its height to 25, as shown in figure 1.19.
Nowyou've learnedwhy there's no SVG <square>. The color, stroke, and transpar
deter
ency of any shape can be changed by adjusting the style of the shape, with fillstroke -
mining the color of the area of he shape and stroke, stroke-width,
dasharray deternining its outline.
Notice, though, that the inspected element has a measurenent of 27 px x 27 px.
That's because the lpx sroke is drawn on the outside of the shape. That makes sense,
still be 27 px
onceyou knowthe rule, but if youchange the stroke-width to 2px it will
x 27 px. That's because the stroke is drawn evenly over the inside
and outside borders,
something to remem
as seen in figure 1.20. This may not seentoo big adeal, but it's
I when you're rying to line up your shapes later.

and 5-px strokes. Though these


Figure 1.20 The same 25 x 25 <rect> with no, 1px, 2-px, 3-px, 4-px, the same width and height
third report
are drawn on a retina screen using haf-pxels, the second and
(27 px x 27 px) as the fourth and fifth (29 px x 29 px).
CNAPTER
22
vngle to the tolowihe
paramcters of he
Change the stvie rokeVtntI owerl
Lye:
jxst
wi lt h.
ll:puryle strke d onplex
visnaliredthe
suceesstull and atbugu.
Congrtulations'You'e now
ugl
nomeon known as
shapes SVG
<TEXT>
capaciiv to write Iext as well as IeN,
elements,Nso it's primarilthougih,
provides the HIML
SVG
formating support foundin <tspany elements in
have the formatting, voucan nest
do basic
If you do want to
<G> GROUPING ELEMENT

or group element is distinct fromthe SVG elements we've


docsn't exist as disc1ussed
a bounded space. i tha
The
has
<g>
no graphicl representation and
elements. You'll want to use <g elements extensively lustead,
ls
when
cIe
logical gTouping of np of several| shapes and text. For
objects that are made rinstance,
ing graphical circle with alabel above it and move the label and the cirle at
it
wantedto have a them inside a <g> elemen:
you'd place
sane tine. then
<g
<Cirle r "2"
Label</text
<text>This circle's

adjust the trans form attribute nts)


<g

your canvas requires yOu to


Moving a<q> around atuibute is more intinidating than the
varosss
<g> clenent. The transform
it accepts astructured description in text of how ou w
butesof shapes because translate(0,which accepts apir of coo
(ransfomashape. One of tlhose strucuresis defined by the values in tranet
element to the xy position
dinates that move the
pixels to the right and 50 pixes dowo
(x.y). II you want to move a <g> clement O0 Th
to transform="translate (100,50)
then vou need to set its transform atribute
so you canchange the rendered seal
Iransform at°ibute also accepts a scale() seting these seings in
listing 1.3. Youcan see
of the shape as you cn see in the example in results shown in figure 1.21.
action by modifying the previous example witlh the

Listing L3 Grouping SVG elements


<g>
<CirCle r= "2"/>
<text>This Circle's Label </text

<g transfOrm="translate(1 00, 50) ">


<Circle r"2
<text>This Circle's Label</text>

g>
<g trans foR "translate(l00,400) scale(2.5)">
<C1rCie ra "2"/
KLext>Thig circle6 Label</text >
The pouer of HTMLS 23

No transtorm:
Like all SVG elements, the <g> is
drawn at the 0,0 position. The resultby indefault
this case
is that the graphics are
drawn such that you only
see a tiny piece of the bottom
circle, and none of the right corner of the
label text.

Translate(100,50):
The entire <g> element is
moved l00 pixels to the Labcl
(along the x-axis) and 50right
pixels
down (along the y-axis). The
child elements are drawn
from this position.

Translate(|
The <g> 0element
0,400)Scale(3.5):
is moved
to XY position l00,400, lining
it up along the y-axis with the
above <g>,and the child
elements are drawn from
A Label
there at 3.5 times their size.

Flgure 1.21 AllSVG elements can be affected by the transforn attribute, but this s particularly
salient when working with <g> elements, which require this approach to adjust thelr positlon. The
chld elements are drawn by using the position of their parent <g> as their relative 0,0 position. The
scale () setting in the transform attribute then affects the scale of any of the size and position
attributes of the child elements.

<PATH>

Apathis an area determined by its dattribute. Paths can be open or closed, meaning
the last point connects to the first if closed and doesn't if open. The open or closed
nature of a path is deternined by the absence or presence of the letter Zat the end of
the text sring in the d attribute. It can sill be filled either way. You can see the differ
ence infigure 1.22 (he code for which is shown in the following listing).
sting 1.A SVG path and closing
<path stylez fill :none; stroke:gray;stroke- width:4px; "
d="M 10, 60 40. 30 50,50 60,30 70,80" transform="translate(0,0) />
<path style-"fill:black; stroke:gray; stroke-width:4px;"
CHAPTER1 An introduction to D3.js

30 70, 80-
dr "M20,60 40. 30 5C 50 60, transtorm="transl
patstyletiil :none:strOke:gray; stroke-width: 4px ;
de"N 10.60 s0, 30 50,5O 60.30 70, 80Z"
<path styl fill :black:stroKe:gray;stroke
transfcrm=- "translate(0, 200)
-width: 4px:
late(0,100)
40.3050.50 60, 30 70, 80Z transform=
d- *N 10, 60
-"translate(0,,300) >
Open- unfilled:
Path elements are by default
fitted with no stroke. You need
te set the ill styBe to "none" and <path style="it:
stroke and stroke-width styie if
you want to draw itas a line. :none;stroke:gray;stroke width:4px"
d="M 10,60 40,30 50,50 60,30 7o.80
transform="transiate(0,0)" is
Open -flled:
An open path can be filled just <path style="fit::biack;stroke:gray;stroke-width:4px*
like a ciosed path, with the fill d="M 10,60 40,30 50,50 60,30 70.80
area defined by the same area transform="translate(0,100) />
that would be bounded if the
path were closed.

Closed - unfilled: <path style="fill:none;stroke:gray;stroke-width;4ny.


d="M 10,60 40,30 50,50 60,30 70.80Z"
Apath willalways close by transform="translate(0,200)" />
drawing a line from the end
point to the start point.
Ciosed- fitted: <path style="fil:black;stroke:gray;stroke-width:4py-*
d="M 10,60 40.30 50,50 60,30 70,80Z"
Notice the stroke overlaps transform="translate(0,300)" />
the fill area slightly.

Figure 1.22 Each path shown here uses the samne coordinates In ts d attribute, with the onty
iierences between them being the presence or absence of the letter Z at the end of the
defining the dattribute, the settings for fill and stroke, and the position via the transformtext string
attribute.

Aithough someimes you may want to write that d attribute yourself, it's more likely
that your experience crafing SVG will come in one of three ways: using
geomeric
primitives such as circles, rectangles, or polygons, drawing SVG using a vector graphics
editor like Adobe Illustrator or Inkscape, or drawing SVG
parametrically using hand
Written constructors or built-in constructors in D3. Most of this book focuses on
using
D3 to Create SVG, but don't overlook the possibility of
creating SVG using an
appication or aother library and then manipulating them using D3, like external
we'll do
using d3.htnl in chapter 3
L34 CSS
CSS are used to style the elements in the DOM. A style
sheet can exist as a separate
file that you incdude in your HTML page or can be
embedded
page. Style sheets refer to an ID, class, or type of element and directly the HIMt
in
ance of that clenent. The terminology used to define the determine he appe
styie is a CSS selector aiu
well inThe </htm> </body> <body>
</style> rect { circle ( src="d3.v4,min.js"></script>
.tentative
.active i { inactive, <SCript
<styles . <!doctype
html>
<html> d3ia.html (mat ie
.Style(opacity,
about the </àiv>
</Svg> <ect
<ircle <g> <svg <div darkgray: fill: fill:
red;
stroke-dasharray: 1; stroke-dasharray:
stroke:
black;
stroke-width:
ápx; opacity:.5; arkgray;
stroke:
stroke-width:
2px;
5:5 Listing
sae
figure
way Style asresults <polygon<path are
other the style="width:50Opx;
ciass="active" height:500px;id="infovi
border:lpx 15 to
sheets
an 1.23, .tentative (
applied ype
element class stack lass="acti
d= include
complex ciasS="inactive" "M A of
can you 10, sample selector
attribute on .5) to
see each 60 zDiv a
also
CSS looks refer that ve 40, "> web style toonly
x*410" set used
selectors when active. iother,
of tentative" 30 page sheet, a The
ts 50,50 th e
single
to style in power
so points-"80, later)(we'll
dynamically
content The with as
onacity the
a y="200"
shown element)
the state when
is 60,30 fixed CSS a of
inuser Cy" work style d3.select)
set content rules HTML5
more of on in of
the byyou width"100" 100" 70,
sheet an
mouses the 400 80" adding for the
detail element, examine cx=*200"
120,400 /> our
of our weThe followingelement by
reference more elements can using
syntax.
page reference
inover lightgraysolid;"> use
a the height=50" >
listingd3.select
to
book that withso rectangle to
r="30"160,440 that
to 50%. You
code the
can
element. : rect
devoted /> in D3 Let's
hover 120,480 library
our (#SomeElement) set
element, in
the app update inline
toYou you so
style 60,
that can 460" youl siyres
can as 25
subject change sheetshown
learn />
as
CAPTEs 1 An introduction to D3.js

v chtmi lements Network Sources


data--ember-extension

chead></head>
v <body>
cdiV id="vizcontainer"
<path
60,30 d="M
70,80"10,60
></path>
40,30 50
<polygon class="inact ive
points="80,
120,480 400
60,460" ></polygon>
120,400
<circle cy=" 100"
"30''></circle> cx="200
160,440
<rect class"active" x=*41@:
"299 width="100"
|rect. active 9 he ight=
"50"></rect>
</g>
</svg>
V

</div
<footer></ footer>
</body>
</html>

html body divtvizcontainer svg


ConsoBe Search Emulation Rendering
Figure 1.23 Examining an SVG
CSS styie appled to rectangle in the consoie shows that t inherits its
<rect> types and its stroke styte from fillstyle from the
the .active class.
For this book, we'll
focus mostly on using CSS
change style. The most useful way classes
to do this is to have and IDs for selection and to
ticular stylistic changes and then CSS classes associated with
class of an element, which is change the class of an element. You can par
the class attribute. The an atribute of an
element, by
change the
circle shown in figure 1.24 is selecting and
classes: .activeand
.tentative. affected by two modifying
In listing 1.5 we see a
and inacive all couple of possibly overlapping classes, overlapping
applying
circle in figure I.23). When differentstyle changes to your shape (such with tentative, active.
as the
you can overwrite the class
an element needs oniy be
attribute entirely: assigned to highlighted
one of these
3.select {"circle") .attr ("class",
classes,
"tentative");
The resuits, as shown in figure
1.25, are
ciass aiiribute to the value you set. But what we'd expect. This
times an elenent is both active and elements can have Overwrites
Imuliple the entire
the page and take advantage of the tentative
or inactive and cBasses, and some-
to add or reTIOVE a ciass fron
helper function
the classes in an element.
d3 . classed (), tentative,which reload
so ler's
d3. select("circe).ci assed{"active",
true)
allows you
27
The pouer of HIML.5

QElementsi Nerwork Sources Timelint


Vchtml data-enbe r-ex tens ion"1">
chead></head>
V <div 1d="vizcontainer">

<path d"M 10,60 40,30 50,50


60,30 70,80"></ pat h>
Circle.active .tentat ive 580x 58px <polygon class"inactíve"
po Lntsn"80, 400 120,40e 160,440
120, 480 68,468"><fpolygon>

<Circle Cy100 Cx200 r


"30" classa"active
tentative"></circles
<rect class='" active" x="410" ym
"200" width='"100" height=
"50"></ rect>
</g>
</svg>
</div>
<footer></footer>
</body>
</html>

svg 9 circle.active.tentative
Console Search Emulation Rendering

Figure 1.24 The SVG clrcle has its fl value set by its type in the style sheet, with its opacity set by
ts membership in the .tentat ive class and its stroke set by its membership in the . active class.
Notice that the stroke settings from the .tentative class are overwritten by the stroke settings in
the later declared .active class.

By using .classed (), you don'toverwrite the existing attribute, but rather append or
remove the named class from the list. You can see the results of two classes with con
flicting styles defined. The active style overwrites the tentative style because it occurs
later in the style sheet. Another rule tO remember is that more specific rules overwrite
Inore general rules. There's more to CSs, but this book won't go into that.
By defining style in your style sheet and changing appearance based on class mem
bership, you create code that's more maintainable and readable.You'll need to use
inlinestyles toset the graphicalappearance of a set of elements to a variety of different
values, for example,changing the fillcolor tocorrespond to acolor ramp based on the

Flgure 1.25 An SVG circle with fWlstyle determined by


its type and its opacity and stroke settings detemined
by ts membershlp in the tentative class
to D3,js
CNAPTER 1 An intoduction
functionalityin acttion later
You'llsee that
duaboundto hat
set
data.
ofelements
But as a general
deal wih bound trditional classesand states
when vou can'uNe
deined in
s1ves
rule, sctting inline syle should
a sheo
only
whenwoN
L3.5 avaScript libraries in JavaScript, provides
D3, like many
intormation visualization
creating and molifying web page
elements. On top of
abstract the process of link data and web page elements in a way that
funcioushal,
tc
i
drawing
providesand to
updating of these SVG elements reusable and maintainable. But these
mechanisns makes
le
mechanisms are also applicable to more traditional HTML elements such as para-

When
graphs andwriçng
dis. JavaScript with D3, voushould familiarize yourself with two subjects.

method chaining and arrays.


METHOD CHAINING
examples written in JavaScript, use method chaining exten-
sively. Methodlike
D3 examples, many also known as function chaining, is facilitated by returning
chaining,
wi
the successful completion of functions associated
the method itself with method chaining isto think of how we talk and refer to
method. One way to think of and you asked
Imagine vou were talking to someone at a party, about
each other.
another guest:
"What's her name?"
"Her name is Lindsay."
"Wheredoes she work?"
"She works at Tesla."
"Where does she live?"
"She lives in Cupertino.
children?"
"Does she have any
Yes, she has adaughter."
"What's her name?"

last question would be "Lindsay"? Of course not.


Do you think the answer to that
though all the previous
refer to Lindsay's daughter, even
You'dexpect the answer to Method chaining is like that. lt returnsthe same func
questions referred to Lindsay. returnsthe new
you use getter and setter methods of that function and
tion as long as
call a method that creates somnething new. Method chaining is
funcion when you like this written on one
which means you'll see something
used a lot in D3 examples, something written on multiple lines
to
line or fornatted (but functionally identical) (Wow). append
.enter () . append "div").ntmi
d3.selectA1l ("div"}.data (some Data) 900):
Wow"i.styie ("font-weight"
span"). html ("Even More
hn
line is the same as the following code. The oniy change is in the use of
That
breaks,which JavaScript ignores:

You might also like