D3.js Tutorial - Courses.cs.washington.edu

Transcription

D3.js TutorialKaitlyn Zhou & Younghoon KimSlides by Jane Hoffswell & Kanit "Ham" Wongsuphasawat(Many thanks to them!)

ResourcesTutorials: An older version of UW D3 tutorial: https://uwdata.github.io/d3-tutorials/Let’s Make a Bar Chart: https://bost.ocks.org/mike/bar/References: JavaScript: The Good ript the good parts.pdfInteractive Visualization for the 00345/index.html

Follow iewer.htmlDownload your own copy pages/live.zip(Click “raw” to download)

Background

What is D3.js?Data are bound to DOM elements to make Data-Driven Documents

What is D3.js?DATA are bound to DOM elements to make Data-Driven Documents

What is D3.js?Data are bound to DOM ELEMENTS to make Data-Driven Documents

What is D3.js?Data are BOUND to DOM elements to make Data-Driven Documents

Example:Titanic Passengers

Example

Example

Testing

Make a webpage python -m SimpleHTTPServer 8000To test your web page, run the above command from the folder in which yourproject is located. If your page has an index.html file, it will appear automatically.Otherwise, add the desired html file to the end of the web address or navigate to itin the browser.

Debugging CSS, HTML, and JavaScriptUse the JavaScript Console in your browser.In the JavaScript console, you can view theDOM including assigned properties and theunderlying style of elements. When youselect an element, you can change theproperties to prototype changes beforeadding them to your program.

Debugging CSS, HTML, and JavaScript

1. Getting StartedLink: .html

index.htmlWe can start by defining a simple web page,which has a header (h1) and an svg element thatwill hold our visualization. In the style tags, wecan add CSS styling for both elements defined inthe HTML.CSS StyleHTML

2. Adding ElementsLink: tml

Manually specifying elementsWe can manually add elements to the DOM, andspecify properties such as the x and y position,and the title (which appears as a tooltip onhover).Elements can be added directly to the svg /svg element, or to g /g svg groups.They will inherit the properties of their parentgroup (like location and orientation).

Positioning ElementsKeep in mind that the origin for positioningelements is the upper left corner.(0,0)(60,25)(120,465)

3. SelectionsLink: tion.html

Selecting elementsd3.select() and d3.selectAll() can be used toaccess DOM elements by name, class, id, ormany other css selectors. d3.select() selects onlythe first element that matches the css selectorswhile d3.selectAll() selects all matchedelements.

Modifying selected elementsYou can use access and modify the properties ofselections with attr(), text(), style(), and otheroperators. Most D3 selection methods return theselection, allowing us to chain the operator calls.

Appending elementsThrough append(), we can add new elementsanywhere in the DOM. We can then useoperators or CSS to set the properties of theelement.We can also get rid of elements with remove().Finally, we can store selections in variables forfuture use.D3 selections page extremely helpful!

4. Data BindingLink: ng.html

“Thinking with Joins” - Mike BostockReference: https://bost.ocks.org/mike/join/

BindingWe can use the data() function to bind data to aselection.We can also use data() or datum() to access thedata that belong to a selection.

elect all of our circles (currently we don’thave any).Bind our data (in this case, 5 rows worth)Enter each new datum from our selection.Append a new DOM element. There arenow 5 new elements, each with their ownunique data.Append titles to the new elements.Merge our new elements into our originalselections.Set attributes with operators, usinganonymous functions.

Select all of our circles (currently we don’thave any).Bind our data (in this case, 5 rows worth)Enter each new datum from our selection.Append a new DOM element. There arenow 5 new elements, each with their ownunique data.Append titles to the new elements.Merge our new elements into our originalselections.Set attributes with operators, usinganonymous functions.234567

5. ScalesLink: s1.htmlLink: s2.html

Specifying scalesTo position the dots, we can manually specify thex and y position attributes, but this process canbe tedious and error prone for complexattributes:

Specifying scalesScales are functions that map from a domain to arange(a domain of chart).Anonymous functions can be used toparameterize the element's attributes using theelement's data. Anonymous functions can havetwo parameters d (our bound datum) and i (theindex of our datum).Using a scale:Manual cing-d3-scale-61980c51545f

More scale typesd3.scaleLinear create a linear mapping. You canalso have d3.scaleLog, d3.scaleSqrt, and so on.You can also specify ordinal (which includenominal data types) and temporal scales. Notethat the range() does not have to be a set ofnumbers; it can also be colors or strings.Check the D3 Scales page for more information.Note: d3.scaleLinear is new to D3v4 andreplaces d3.scale.linear. This is true for all ofthese camelCase method names.D3 also has built in scales for categorical colors:d3.schemeCategory10()#1f77b4 #ff7f0e #2ca02c #d62728 #9467bd#8c564b #e377c2 #7f7f7f #bcbd22 #17becf

6. Axes & LegendsLink: htmlLink: ds.html

Creating axesAxes can be generated based on the scales inyour visualization. Axes are defined based ontheir position using d3.axisTop, d3.axisBottom,d3.axisRight, or d3.axisLeft.Note: each of these constructors is a function; tocreate our axis, we create or select the elementwhere we want to place it, and then use call() toapply the function to it. For more information oncall(), see this page.See the D3 Axes page for more information.Scale:Specify axis:Draw axis:

Labeling axesLabels can be added to your visualization byadding text marks. As with any other mark, youcan programmatically specify both HTMLattributes and CSS styles.

LegendsLegends can be constructed just like the otherelements of your visualization: by creating a newset of marks and using scales to style theattributes.In addition to the rect for the legend mark, wecan append text to create the legend labels.

7. Events & TransitionsLink: s.htmlLink: sitions.html

Reacting to eventsEvent listeners can be added to marks to react toevents on the underlying selection using the on()method. The on() method takes the event nameand a callback function that is triggered everytime the specified event happens.An anonymous function can be used as thecallback for the event listener. The input to thefunction d represents the underlying data of themark. The scope, this, corresponds to the DOMelement.

8. Loading FilesLink: html

Loading data from external filesData can be loaded from many types of externalfiles using commands such as d3.csv, d3.json,d3.tsv.The D3 functions additionally support callbackfunctions for dealing with the resulting data orerror cases.

Loading data from external filesWhat to do per row:(Including creating aliasesor specifying data type.Callback functionError handlingWhat to do with all returnedrows (including sorting,filtering, or

9. Enter/Update/ExitLink: .html

RebindingThree things can happen when we call data():Update: We want to change the elements wealready have.Enter: We have new data.Exit: We have data that is no longer bound.

RebindingGood practice to have an update function.1.2.3.4.5.Bind or rebind dataPerform update operationsPerform operations on enter setPerform operations on update enter setsPerform exit operations

1. UpdateThings I want to happen to all of our data,whenever the function is called. Potentiallyoverwritten by later steps.

2. EnterThings I want to happen to all new dataCan use append() to make new elements fornew data.

3. Enter UpdateThings I want to set initially. Can use transitionsto have attributes fade in after creation.Note: In D3v4 you need to merge the enter setinto your update selection (scatter) to performupdates on the enter and update set.

4. ExitThings I want to happen to old dataCan use transitions to make old data fade awayCan use remove() to keep only elements that arebound to our current data.

Key bindingWith only one argument, binding will only keeptrack of the amount of data we have.If we always have the same amount of data, thennothing will “exit.”Can use a argument to specify unique identifiersfor data, to define whether data should enter orexit.Here, our key is the index (row number) of thedata in our original csv. Passenger name is notunique, and so would not make a good key.

ConclusionCheck out https://bl.ocks.org/ for d3 snippets showing important concepts.Check out the Resources page for additional tutorials and resources.

Feedback?

Debugging CSS, HTML, and JavaScript Use the JavaScript Console in your browser. In the JavaScript console, you can view the DOM including assigned properties and the underlying style of elements. When you select an element, you can change the properties