Adobe Scan Jun 22, 2023
Adobe Scan Jun 22, 2023
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
Charts
Interactivity basics
(chapter 2)
Interactivity
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
O Bdvance search used to be better Oreferences elsewhere in scholarship on and off the web to find titles
Google O
O googie ngrams
O is hard to use
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,
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.
Select elements
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.
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
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)
Edit as HTML
Copy C5S Path
Copy XPath
Copy
Cut
Delete Node
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
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>
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);
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
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.
Figure 1.17 The commands to draw an SvG path (git) and the resulting graphic (left)
I8 CHAPTER 1 An introduction to D3.js
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
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
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>
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.
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.
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
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>
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
When
graphs andwriçng
dis. JavaScript with D3, voushould familiarize yourself with two subjects.