D3: The Crash Course - GitHub Pages

2y ago
18 Views
2 Downloads
2.72 MB
98 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Harley Spears
Transcription

D3: The Crash Courseaka: D3: The Early Sticking Pointsaka: D3: Only the BeginningChad StolperGoogle(graduated from Georgia Tech CS PhD)Chad StolperCSE 6242 Guest Lecture1

https://vimeo.com/29862153Chad StolperCSE 6242 Guest Lecture2

Chad StolperCSE 6242 Guest Lecture3

Why should you learn D3?Chad StolperCSE 6242 Guest Lecture4

If you visualization/system/tool willbenefit from interactivity.Otherwise, use anything you want(e.g., tableau, excel, python:seaborn, R:ggplot2, etc.)More online discussion: https://news.ycombinator.com/item?id 11995332From D3 creator: -ae63c276e958Chad StolperCSE 6242 Guest Lecture5

Chad Stolper6

This lecture is about D3 v3 Ver4/5 is the latest, but has ”breaking” changes.Most D3 examples/tutorials are still using v3Ver4 vs ver3: https://iros.github.io/d3-v4-whats-new/#1Upgrading Ver3 code to ver4 pgrading-d3-from-v3-to-v4/Chad Stolper7

Chrome Inspector and Console Open the webpageRight-click on anythingClick “inspect”Open the console too, so you can see theerror messagesChad StolperCSE 6242 Guest Lecture8

Starting a Local Web Serverhttps://github.com/d3/d3/wikiNecessary for Chrome, not for Safari or Firefox(This is a security measure: to prevent reading from your file systems) Python 2.x- python -m SimpleHTTPServer 8000 Python 3.x- python –m http.server 8000 http://localhost:8000Chad StolperCSE 6242 Guest Lecture9

If you’re new to JavaScript prepare for a lot of confusion (wat?)and hair pullingI’m serious.Chad .jpgCSE 6242 Guest Lecture10

If you’re new to Javascript ing 1:20)Chad StolperCSE 6242 Guest Lecture11

Javascript 101 All variables are global, unless declaredusing var- x 300 (global)- var x 300 (local) Semicolons are optional “text” is the same as ‘text’ JS arrays and objects are almost exactly thesame syntax as python’s lists [ ] and dicts { } object.key is the same as object[‘key’] Print to the console using console.log( )Chad StolperCSE 6242 Guest Lecture12

Javascript 102: Functional Programming Javascript supports functional programming- Functions are themselves objects- Functions can be stored as variables- Functions can be passed as parameters As in HW1: hart D3 uses these abilities extensively!Some people say javascript is a “multi-paradigm” programming ad StolperCSE 6242 Guest Lecture13

What does that mean?Passing Math.sqrt (a function)as a Web/JavaScript/Reference/Global Objects/Array/mapChad StolperCSE 6242 Guest Lecture14

MDN – the BEST Javascript reference Mozilla Developer Network ript/Reference (Easier: google “ command mdn”)Chad StolperCSE 6242 Guest Lecture16

Method Chaining “Syntactic Sugar” paradigm where eachmethod returns the object that it wascalled ongroup.attr("x",5).attr("y",5); //returns groupis the same asgroup.attr("x",5) //returns groupgroup.attr("y",5) //returns groupChad StolperCSE 6242 Guest Lecture17

SVG BASICSSVG Scalable Vector Graphicshttps://en.wikipedia.org/wiki/Scalable Vector GraphicsChad StolperCSE 6242 Guest Lecture18

(0,0)yxChad StolperCSE 6242 Guest /media/RvB/Descart-weeping.png.html

SVG BasicsSVG - XML Vector Graphics(Scalable Vector Graphics)Chad StolperCSE 6242 Guest Lecture21

SVG Basics XML Vector Graphics- Tags with Attributes- circle r 5 fill "green" /circle W3C Standard- http://www.w3.org/TR/SVG/ Supported by all the major browsersChad StolperCSE 6242 Guest Lecture22

SVG Basics svg circle rect path g text (after I’ve talked about D3)Chad StolperCSE 6242 Guest Lecture24

svg element Overarching canvas (optional) Attributes:- width- height Create with body div id "vis" svg /svg /div /body - d3.select("#vis").append("svg")Chad StolperCSE 6242 Guest Lecture26

circle element Attributes:- cx (relative to the LEFT of the container)- cy (relative to the TOP of the container)- r (radius) (optional) Attributes:- fill (color)- stroke (the color of the stroke)- stroke-width (the width of the stroke) Create with- .append(“circle”)Chad StolperCSE 6242 Guest Lecture27

rect element Attributes:-x (relative to the LEFT of the container)y (relative to the TOP of the container)width (cannot be negative)height (cannot be negative) (optional) Attributes:- fill (color)- stroke (the color of the stroke)- stroke-width (the width of the stroke) Create with- .append(“rect”)Chad StolperCSE 6242 Guest Lecture28

origin(0,0)yxheightwidthChad StolperCSE 6242 Guest /media/RvB/Descart-weeping.png.html

Rather than positioning each element, what if wewant to position (or style) a group of elements?Chad StolperCSE 6242 Guest Lecture30

g element Generic container (Group) element Attributes- transform- (fill,stroke,etc.) Create with:- var group vis.append(“g”) Add things to the group with:- group.append(“circle”)- group.append(“rect”)- group.append(“text”)Chad StolperCSE 6242 Guest Lecture31

CSS Selectors Reference By ID: #vis à tag id "vis" By tag name: circle à circle By class name: .canary à tag class "canary" By attribute: [color "blue"] à tag color "blue" And many more ways- http://www.w3schools.com/cssref/css selectors.aspAnd any combinations - ANDcircle.canary à circle class “canary” - ORcircle, .canary à circle circle class “canary” tag class “canary” Chad StolperCSE 6242 Guest Lecture32

AND NOW D3 Chad StolperCSE 6242 Guest Lecture33

Mike Bostock and Jeff Heer @ Stanford2009- ProtovisChad StolperCSE 6242 Guest Lecture34

Mike Bostock and Jeff Heer @ Stanford2009- ProtovisChad StolperCSE 6242 Guest Lecture35

Mike Bostock and Jeff Heer @ Stanford2009- Protovis2011- D3.jsChad StolperCSE 6242 Guest Lecture36

Univ. of WashingtonMike Bostock and Jeff Heer @ Stanford2009- Protovis2011- D3.jsChad StolperCSE 6242 Guest Lecture37

New York TimesUniv. of WashingtonMike Bostock and Jeff Heer @ Stanford2009- Protovis2011- D3.jsChad StolperCSE 6242 Guest Lecture38

D3 Grand Reductionist Statements Loading DataEnter-Update-Exit ParadigmScalesAxesLayoutsTransitions and Interaction Where to go from hereChad StolperCSE 6242 Guest Lecture39

D3.js in a NutshellD3 is a really powerful for-loopwith a ton of useful helper functionsChad StolperCSE 6242 Guest Lecture40

D3Declarative, domain-specific specificationlanguage for manipulating the DOMDefine a template for each type of elementD3 draws one element for each data pointChad StolperCSE 6242 Guest Lecture41

Importing D3 html head script src 'lib/d3.js’ charset ‘utf-8’ /script script src 'js/project.js' /script /head body div id “vis” /div /body /html Chad StolperCSE 6242 Guest Lecture42

Importing D3 html head script src 'lib/d3.js’ charset ‘utf-8’ /script script src 'js/project.js' /script /head body div id “vis” /div /body /html Chad StolperCSE 6242 Guest Lecture43

Importing D3 html head script src 'lib/d3.js’ charset ‘utf-8’ /script script src 'js/project.js' /script /head body div id “vis” /div /body /html Chad StolperCSE 6242 Guest Lecture44

Importing D3 html head script src 'lib/d3.js’ charset ‘utf-8’ /script script src 'js/project.js' /script /head body div id “vis” /div /body /html Chad StolperCSE 6242 Guest Lecture45

Assigning the Canvas to a Variablevar vis d3.select(“#vis”).append(“svg”) body div id “vis” svg /svg /div /body Chad StolperCSE 6242 Guest Lecture46

Loading Data d3.csv(fileloc,callback) d3.tsv(fileloc,callback) d3.json(fileloc,callback) fileloc: string file location- “data/datafile.csv” callback: function(rawdata){ }Chad StolperCSE 6242 Guest Lecture47

rawdata from a CSV file[{},{},{]}‘name’: ‘Adam’,‘school’: ‘GT’,‘age’: SU30‘name’: ‘Barbara’,‘school’: ‘Emory’,‘age’: ‘22’‘name’: ‘Calvin’,‘school’: ‘GSU’,‘age’: ‘30’Chad StolperCSE 6242 Guest Lecture48

Problem[{},{},{]}‘name’: ‘Adam’,‘school’: ‘GT’,‘age’: ‘18’ Ages are Strings! They should be ints! We can fix that:‘name’: ‘Barbara’,‘school’: ‘Emory’,‘age’: ‘22’‘name’: ‘Calvin’,‘school’: ‘GSU’,‘age’: ‘30’Chad Stolperfor(var d: data){d data[d]d.age d.age}CSE 6242 Guest Lecture49

Problem[{},{},{]}‘name’: ‘Adam’,‘school’: ‘GT’,‘age’: ‘18’ Ages are Strings! They should be ints! We can fix that:‘name’: ‘Barbara’,‘school’: ‘Emory’,‘age’: ‘22’‘name’: ‘Calvin’,‘school’: ‘GSU’,‘age’: ‘30’Wdata[d] ATfor(var d: data){d d.age mbersChad StolperCSE 6242 Guest Lecture50

rawdata from a CSV file[{},{},{]}‘name’: ‘Adam’,‘school’: ‘GT’,‘age’: �name’: ‘Barbara’,‘school’: ‘Emory’,‘age’: 22‘name’: ‘Calvin’,‘school’: ‘GSU’,‘age’: 30Chad StolperCSE 6242 Guest Lecture51

rawdata from a CSV file[{},{},{]}‘name’: ‘Adam’,‘school’: ‘GT’,‘age’: �name’: ‘Barbara’,‘school’: ‘Emory’,‘age’: 22‘name’: ‘Calvin’,‘school’: ‘GSU’,‘age’: 30Chad StolperOk, so let’s mapthis data to visualelements!CSE 6242 Guest Lecture52

D3Declarative, domain-specific specificationlanguage for manipulating the DOMDefine a template for each elementD3 draws one element for each data pointChad StolperCSE 6242 Guest Lecture55

Enter-Update-Exit The most critical facet of how D3 works If you remember nothing else from today,remember this. “Enter-Update-Exit” “Enter-Update-Exit” “Enter-Update-Exit”Chad StolperCSE 6242 Guest Lecture56

Enter-Update-ExitPattern: Select a “group” of “elements” (e.g., circles) Assign data to the group Enter: Create new elements for data points notassociated with any elements yet (and set constant orinitial attribute values) Update: Set the attributes of all the elements based onthe data Exit: Remove elements that don’t have data anymoreChad StolperCSE 6242 Guest Lecture57

.enter( ) and .exit( ) .data( [1,2,3,4] )- Enter: [1,2,3,4]- Update: [1,2,3,4]- Exit: [ ] .data ( [1,2,3,4,5,6] )Old ElementsNew DataExitEnter- Enter: [5,6]- Update: [1,2,3,4,5,6]- Exit: [ ]Update .data ( [1,2,3] )- Enter: [ ]- Update: ?- Exit: [4,5,6]Chad StolperCSE 6242 Guest Lecture58

.enter( ) and .exit( ) .data( [1,2,3,4] )- Enter: [1,2,3,4]- Update: [1,2,3,4]- Exit: [ ] .data ( [1,2,3,4,5,6] )Old ElementsNew DataExitEnter- Enter: [5,6]- Update: [1,2,3,4,5,6]- Exit: [ ]Update .data ( [1,2,3] )- Enter: [ ]- Update: [1,2,3,4,5,6]- Exit: [4,5,6]Chad StolperCSE 6242 Guest Lecture59

.enter( ) and .exit( ) .enter( )Old ElementsNew Data- New data pointsExitEnter .exit( )- Elements to be removedUpdate .enter() and .exit() only exist when .data()has been calledChad StolperCSE 6242 Guest Lecture60

Can be hard to grok:You can select groups of elements thatDON’T EXIST YEThttp://bost.ocks.org/mike/join/Chad StolperCSE 6242 Guest Lecture61

Still confused?Excellent interactive demo to explain troduction/master/index.htmlFull tutorial:https://medium.com/@c had StolperCSE 6242 Guest Lecture62

Data Key Functions .data(rawdata) defaults to assuming that theindex of the point is the key .data(rawdata, function(d,i){ }) allows you toset a key functions e.g.- .data(rawdata, function(d,i){ return d.id; })- .data(rawdata, function(d,i){ return d.name; })Chad StolperCSE 6242 Guest Lecture63

E-U-E Pattern Templatevar group vis.selectAll(“rect”).data(rawdata) //rawdata must be an array!group.enter( ).append(“rect”) //ENTER!.attr( ).style( )group //UPDATE!.attr( ).style( )group.exit( ).remove( ) //EXIT!Chad StolperCSE 6242 Guest Lecture64

WARNING!!!!Chad StolperCSE 6242 Guest Lecture65

E-U-E Pattern Templatevar group vis.selectAll(“rect”).data(rawdata) //rawdata must be an array!group.enter( ).append(“rect”) //ENTER!.attr( )Many online examples.style( )group //UPDATE!.attr( ).style( )group.exit( ).remove( ) //EXIT!Chad StolperCSE 6242 Guest Lecture66

E-U-E Pattern Templatevar group vis.selectAll(“rect”).data(rawdata) //rawdata must be an array!group.enter( ).append(“rect”) //ENTER!.attr( )Many online examples.style( )drop the variable name beforegroup //UPDATE!.enter().attr( ).style( )group.exit( ).remove( ) //EXIT!Chad StolperCSE 6242 Guest Lecture67

E-U-E Pattern Templatevar group vis.selectAll(“rect”).data(rawdata) //rawdata must be an array!group.enter( ).append(“rect”) //ENTER!.attr( )Many online examples.style( )drop the variable name beforegroup //UPDATE!.enter().attr( )I highly recommend you don’t!.style( )group.exit( ).remove( ) //EXIT!Chad StolperCSE 6242 Guest Lecture68

.attr( ) The Attribute Method Sets attributes such as x, y, width, height,and fill Technical details:- group.attr(“x”, 5)- rect x “5” /rect Chad StolperCSE 6242 Guest Lecture69

.attr( ) and Functional ProgrammingInput[ {size: 10}, {size: 8}, {size: 12.2} ]We want 3 rectangles: rect height “10” x “5” /rect rect height “8” x “10” /rect rect height “12.2” x “15” /rect .attr(“height”, function(d,i){ return d.size })d: the data point.attr(“x”, function(d,i){ return (i 1)*5; })i: the index of the data pointChad StolperCSE 6242 Guest Lecture70

text elements I’m going to apologize in advance here forthe lousy job the W3C did with the text definition. You’re going to have to just eithermemorize these things or keep referringback tohttp://www.w3c.org/TR/SVG/text.html(first Google hit for “svg text”) like I do.Chad StolperCSE 6242 Guest Lecture71

text elements Extra Method in D3- .text(“Your Text Goes Here”)- tag Your Text Goes Here /tag Attributes-x-y Styles- text-anchor: start, middle, end- dominant-baseline: [nothing], hanging, middleChad StolperCSE 6242 Guest Lecture72

text-anchor styleWhere is (0,0)?This is my line of text.startChad StolpermiddleCSE 6242 Guest Lectureend73

dominant-baseline styleWhere is (0,0)?hangingmiddledefaultThis is my line of text.Chad StolperCSE 6242 Guest Lecture74

text t.htmlChad StolperCSE 6242 Guest Lecture75

The .style() FunctionLike attr, but for the style attribute Inline CSS p2”,“val2”).style(“prop3”, function(d,i){ }) ele style “prop1: val1; prop2: val2;” Chad StolperCSE 6242 Guest Lecture76

text d){return d.name}).attr(“x”, function(d,i){return i*5}).attr(“y”, function(d,i){return ”).style(“text-anchor”, “middle”)Need to remember what to use.style and when to use .attrChad StolperCSE 6242 Guest Lecture77

What if you havetwo different types of circles?Chad StolperCSE 6242 Guest Lecture78

Classing CSS Classes- Any number of classes per element- Select using “.classname”blue ta, function(d){return d.id;})blue.enter( �, ��fill”,“blue”)Chad StolperCSE 6242 Guest Lecture79

Scales(e.g., sizing a circle based on data value)Chad StolperCSE 6242 Guest Lecture80

.attr(“height”, function(d){ return d; })can blow up really quickly Chad StolperCSE 6242 Guest Lecture81

Scales D3 has many types of scales I am only going to cover two:- Linear Scales- Ordinal ScalesChad StolperCSE 6242 Guest Lecture82

Linear Scalesvar xscale d3.scale.linear( ).domain( [min, max] ).range( [minOut, maxOut] )group.attr(“x”, function(d,i){return xscale(d.size);})Chad StolperCSE 6242 Guest Lecture83

Min and MaxBut how do you figure out the min and maxfor the domain?Chad StolperCSE 6242 Guest Lecture84

D3A really powerful for-loop with a ton ofuseful helper functionsChad StolperCSE 6242 Guest Lecture85

Min and Max d3.min( [ ] ) à number d3.max( [ ] ) à number d3.extent( [ ] ) à [number,number]Chad StolperCSE 6242 Guest Lecture86

Domain & 0-phpapp02/95/d3-17-638.jpg?cb 1404831405Chad StolperCSE 6242 Guest Lecture87

An optional accessor function may be specified, which isequivalent to calling array.map(accessor) beforecomputing the maximum value.d3.max(data.map( function(d){ return d.age; })) // returns the maximum /master/Arrays.mdChad StolperCSE 6242 Guest Lecture88

var maxAge d3.max(data.map( function(d){ return d.age; })) // returns the maximum agevar yscale d3.scale.linear( ).domain( [0, maxAge] ).range( [0, 100] )Chad StolperCSE 6242 Guest Lecture89

Linear Scales You can even keep the same scale, andjust update the domain and/or range asnecessary Note: This will not update the graphicsall on its ownChad StolperCSE 6242 Guest Lecture90

Ordinal Scales D3 has built-in color scales!- (And they’re easy!) var colorscale d3.scale.category10( ) Also available are:-category20( )category20b( )category20c( )(and even a few more)Chad StolperCSE 6242 Guest Lecture91

Ordinal Categorical Scales D3 has built-in color scales!- (And they’re easy!) var colorscale d3.scale.category10( ) Also available are:-Think carefully before using acategory20( )rainbow palette for ordinal data!http://www.mathworks.com/tagteam/81137 92category20b( )238v00 RainbowColorMap 57312.pdfcategory20c( )(and even a few more)Chad StolperCSE 6242 Guest Lecture92

Ordinal Categorical Scales [ {type:'Bird'},{type:'Rodent'},{type:'Bird'} ] var colorscale d3.scale.category10( ) .attr(“fill”,function(d,i){return colorscale(d.type)} rect fill "blue" /rect rect fill "orange" /rect rect fill "blue" /rect Chad StolperBird RodentCSE 6242 Guest Lecture93

D3 also has visual helper-functionsChad StolperCSE 6242 Guest Lecture94

Axesyaxisglyph vis.append("g")yaxis d3.svg.axis( ).scale( yscale ) // must be a numerical scale.orient( 'left' ) // or 'right', 'top', or 'bottom'.ticks( 6 )// number of ticks, default is 10yaxisglyph.call(yaxis)Chad StolperCSE 6242 Guest Lecture95

What if the data is changing?Chad StolperCSE 6242 Guest Lecture97

E-U-E Pattern Templatefunction redraw(rawdata){var group vis.selectAll(“rect”).data(rawdata) //rawdata must be an array!group.enter( ).append(“svg:rect”) //ENTER!.attr( ).attr( )group //UPDATE!.attr( ).attr( )group.exit( ).remove( ) //EXIT!}Chad StolperCSE 6242 Guest Lecture99

E-U-E Pattern Templatefunction redraw(rawdata){var group vis.selectAll(“rect”).data(rawdata) //rawdata must be an array!group.enter( ).append(“svg:rect”) //ENTER!.attr( ).attr( )group.transition( ) //UPDATE!.attr( ).attr( )group.exit( ).remove( ) //EXIT!}Chad StolperCSE 6242 Guest Lecture100

Transitions CSS3 transitions with D3 aremagical! D3 interpolates values for you Chad StolperCSE 6242 Guest Lecture101

Transitionsrect.attr(“height”, 0)rect.transition( ).delay( 500 ) //can be a function of data.duration(200) //can be a function of data.attr(“height”, 5) //can be a function of data.style(“fill”,”green”) //can be a function of dataChad StolperCSE 6242 Guest Lecture102

So transitions allow a vis to be dynamic But they’re not really interactive Chad StolperCSE 6242 Guest Lecture103

InteractionThe on( ) MethodChad Stolpe

D3: The Crash Course Chad Stolper CSE 6242 Guest Lecture 1 aka: D3: The Early Sticking Points aka: D3: Only the Beginning

Related Documents:

May 02, 2018 · D. Program Evaluation ͟The organization has provided a description of the framework for how each program will be evaluated. The framework should include all the elements below: ͟The evaluation methods are cost-effective for the organization ͟Quantitative and qualitative data is being collected (at Basics tier, data collection must have begun)

Silat is a combative art of self-defense and survival rooted from Matay archipelago. It was traced at thé early of Langkasuka Kingdom (2nd century CE) till thé reign of Melaka (Malaysia) Sultanate era (13th century). Silat has now evolved to become part of social culture and tradition with thé appearance of a fine physical and spiritual .

On an exceptional basis, Member States may request UNESCO to provide thé candidates with access to thé platform so they can complète thé form by themselves. Thèse requests must be addressed to esd rize unesco. or by 15 A ril 2021 UNESCO will provide thé nomineewith accessto thé platform via their émail address.

̶The leading indicator of employee engagement is based on the quality of the relationship between employee and supervisor Empower your managers! ̶Help them understand the impact on the organization ̶Share important changes, plan options, tasks, and deadlines ̶Provide key messages and talking points ̶Prepare them to answer employee questions

Dr. Sunita Bharatwal** Dr. Pawan Garga*** Abstract Customer satisfaction is derived from thè functionalities and values, a product or Service can provide. The current study aims to segregate thè dimensions of ordine Service quality and gather insights on its impact on web shopping. The trends of purchases have

Chính Văn.- Còn đức Thế tôn thì tuệ giác cực kỳ trong sạch 8: hiện hành bất nhị 9, đạt đến vô tướng 10, đứng vào chỗ đứng của các đức Thế tôn 11, thể hiện tính bình đẳng của các Ngài, đến chỗ không còn chướng ngại 12, giáo pháp không thể khuynh đảo, tâm thức không bị cản trở, cái được

CRASH COURSE TEST PREPS: ADVANCED PLACEMENT TITLE ISBN 13 ISBN 10 PAGES PRICE AP Crash Course AP Art History Crash Course 2nd Ed. 978--7386-1200-3 -7386-1200-6 256 14.95 AP Biology Crash Course 2nd Ed. 978--7386-1099-3 -7386-1099-2 224 14.95 AP Calculus AB & BC Crash Course 2nd Ed. 978--7386-1219-5 -7386-1219-7 240 14.95

top crash-types, testers file bugs in Bugzilla and link them to the corresponding crash-type in the Socorro server. Multiple bugs can be filed for a single crash-type and multiple crash-types can be associated with the same bug. For each crash-type, the Socorro server provides a crash-type summary, i.e.,