archive-org.com » ORG » O » OCKS.ORG

Total: 58

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Let’s Make a Bar Chart
    Coding a Chart Manually Now consider how you might create a bar chart without JavaScript After all there are only six numbers in this trivial data set so it s not hard to write a few div elements by hand set their width as a multiple of the data and be done with it Careful observers will note that the three pixel padding here distorts the accuracy of the chart by making the bars longer This can be fixed via box sizing border box or by switching to SVG as we will in part 2 DOCTYPE html style chart div font 10px sans serif background color steelblue text align right padding 3px margin 1px color white style div class chart div style width 40px 4 div div style width 80px 8 div div style width 150px 15 div div style width 160px 16 div div style width 230px 23 div div style width 420px 42 div div That looks like this 4 8 15 16 23 42 This chart has one div for a container and one child div for each bar The child div s have a blue background color and a white foreground color giving the appearance of bars with right aligned value labels You could simplify this implementation even further by removing the containing chart div But more commonly your page will contain content in addition to the chart so having a chart container lets you position and style the chart without affecting the rest of the page Coding a Chart Automatically Of course hard coding is impractical for most datasets and the point of this tutorial is to teach you how to create charts from data automatically So now let s create the identical structure using D3 starting with an empty page that contains only a div of class chart The following script selects the chart container and then appends a child div for each bar with the desired width d3 select chart selectAll div data data enter append div style width function d return d 10 px text function d return d Although partly familiar this code introduces an important new concept the data join Let s break it down rewriting the above concise code in long form to see how it works First we select the chart container using a class selector var chart d3 select chart Next we initiate the data join by defining the selection to which we will join data var bar chart selectAll div The data join is a general pattern that can be used to create update or destroy elements whenever data changes It might feel odd but the benefit of this approach is that you only have to learn and use a single pattern to manipulate the page So whether you re building a static chart or a dynamic one with fluid transitions and object constancy your code remains roughly the same Think of the initial selection as declaring the elements you want to exist see Thinking with

    Original URL path: https://bost.ocks.org/mike/bar/ (2016-04-30)
    Open archived version from archive


  • How To Infer Topology
    org 6409154 Note if two line segments intersect but don t share a point this intersection is ignored The topology only cares how points are connected and whether they are distinct not their positions Junctions are irrespective to order So given two lines ABC and CBA then B is not a junction unless there is some other line that intersects B For the purposes of topology construction we also consider the start and end point of every line to be a junction This simplifies the code slightly and has no detrimental effect because it is not necessary to cut a line at a given junction if the line already terminates at that junction The junctions for the U S state borders can be seen here as black dots bl ocks org 6408918 As you expect the border intersections in the contiguous United States are correctly identified You can see a few additional junctions on the coasts such as on the Gulf of Mexico and Puget Sound These junctions are caused by coastal features that are too small to see in the current map such as adjacent islands that share a single point Independent rings such as the Hawaiian islands have no junctions as before this is because rings can be freely rotated A hashtable is a reasonable way to record neighbors However note that the hashtable can be as large as the input geometry Linear probing provides a noticeable performance improvement over array buckets The process of identifying junctions requires iterating over each line and ring while recording the neighbors of each visited point If a point is subsequently revisited and has a different set of neighbors than before then the point is a junction For example given the two lines ABC and ABD the first time we visit B the neighbors are A C The second time we visit B the new neighbors are A D which is different than before and thus B is a junction 3 Cut With all junctions identified the next step is to cut the lines and rings so that they terminate at the junctions For example if B is a junction then the line ABC is split into two lines AB and BC while the line ABD is split into AB and BD Splitting lines at junctions guarantees that all shared point sequences like AB and AB will be correctly deduped and can be performed by simply iterating over the lines and rings while querying the set of previously computed junctions This animation demonstrates cutting on U S state borders bl ocks org 6409668 Red indicates the section of the ring or line before the cut while the blue indicates the section after the cut The blue part gets successively smaller as the ring is cut at each junction For the first junction encountered on a ring we can rotate the ring so that it starts on the junction eliminating a cut and reducing the number of arcs in the generated topology For

    Original URL path: https://bost.ocks.org/mike/topology/ (2016-04-30)
    Open archived version from archive

  • For Example
    the right edge of the graph But adaptive resampling is scale dependent and so compensates for the length of this curve automatically by adding the necessary points to achieve the desired rendering accuracy By showing examples that demonstrate real world applications of a feature rather than just proving the existence of the feature we make a stronger argument We make it easier for the viewer to imagine incorporating this abstract idea into their own work On the other hand there is a risk when we only show a few sample applications If they are not representative then the viewer might speculate alternative solutions The examples are evidence not proof we have to pick strong evidence to make a strong case A seemingly reasonable alternatives is the conventional solution why not just add more detail to Antarctica bl ocks org 5735770 Cartographically speaking Antarctica is special for two reasons it crosses the antimeridian and it encompasses a pole However these special qualifications are only present in the normal aspect If you rotate the sphere along longitude and latitude suddenly any land mass can present this same challenge Try this now by touching the above map Thus if we ignore the problem of antimeridian cutting then as soon as we rotate the globe then polygons can cross from one side to the other causing these horrible artifacts If you ever wondered why the normal aspect is so entrenched in cartography it s not just cultural imperialism it s a tricky math problem bl ocks org 3788999 D3 instead cuts the antimeridian after rotation So D3 doesn t require precut or presampled input It just works because D3 treats polygons and lines as first class primitives during geographic projection avoiding point based artifacts bl ocks org 4481520 I ll end this sequence with one of my favorite unusual projections Allen Philbrick s interrupted sinu Mollweide uses the sinusoidal projection for the southern hemisphere and the Mollweide projection for the northern hemisphere Both hemispheres are interrupted that is cut into lobes reducing distortion on land masses at the expense of the oceans I m not aware of a practical modern use for this projection But I like that I could use it if I so desired or design a specialized interrupted projection of my own It s critical to surface the assumptions intrinsic to your tools and data and the resulting restrictions in expressivity Attacking those assumptions can dramatically increase your creative freedom To sum up examples are about demonstrating the potential value of ideas Unlike a published graphic you don t have to capture immediate value You merely present an idea that has potential in a way that is accessible to your audience Of course visual tests and explanations are great too But remember that your goal is to inspire your viewer make sure the leap from abstract idea to concrete value is a short one Everyone is a Toolmaker I hope I haven t been speaking in a way that only relates to those of you that consider yourself toolmakers library authors framework builders and the like But if I am maybe that s okay I believe we are all toolmakers if only for ourselves You don t have to be on GitHub to identify tedious tasks and design solutions that makes your process easier more productive or more fun Building tools is the sign of a rational mind Broadly speaking I consider examples an extension of working knowledge a place to take a small idea I ve learned during my work and isolate it an apothecary capturing some precious essence in a glass jar Build enough examples and you have a wide repertoire of ideas to apply in any situation Best of all these ideas are inherently composable and customizable not wrapped in a heavy blanket of abstraction There is an important role for abstraction but designing abstractions is difficult Examples on the other hand are easy and flexible You can dispose of them if you think of something better later Even if you desire a formal abstraction a good set of examples are essential for designing it effectively To illustrate my process here are some examples from my work at The New York Times Among the Oscar Contenders a Host of Connections by Mike Bostock Shan Carter Alicia DeSantis and Josh Keller This was a network graphic for the Oscars It shows the current nominees for the six major awards four acting awards best director and best movie The intent of the graphic was to show the deeply interconnected nature of the Hollywood A list and how success concentrates at the top of the food chain Just the Spielberg Kennedy duo who worked on at least 70 films with Oscar nominations The final layout was static but we initialized the positions using D3 s force layout We then hand tweaked the layout to make the curved edges easier to follow and prettier This is a luxury we have working with static datasets we can incorporate manual edits to improve the output of automated layouts The above image is a screenshot of the internal editor we built for this graphic after repositioning nodes and labels or adjusting Bézier control points you can save the coordinates down to a file that drives the static graphic bl ocks org 4566102 While we did not open source our editor it s specialized to the graphic I created a sequence of examples on how to roll your own Starting with brushing then dragging this series demonstrates how to build a custom layout editor for node link diagrams bl ocks org 4600693 We wanted curved links and my previous force layouts used straight ones Applying a trick I learned from Ryan Alexander you can create curved links with a dummy node between each pair of linked nodes The dummy node serves as a control point for a cubic Bézier an invisible node but participating in the force simulation with repelling charge and momentum And this small

    Original URL path: https://bost.ocks.org/mike/example/ (2016-04-30)
    Open archived version from archive

  • How Selections Work
    data to a selection the data is stored in the DOM rather than in the selection data is assigned to the data property of each element If an element lacks this property the associated datum is undefined Data is therefore persistent while selections can be considered transient you can reselect elements from the DOM and they will retain whatever data was previously bound to them To verify that data is a property of elements see selection datum s implementation Data is bound to elements one of several ways Joined to groups of elements via selection data Assigned to individual elements via selection datum Inherited from a parent via append insert or select While there is no reason to set the data property directly when you can use selection datum doing so illustrates how data binding is implemented You might also find this knowledge useful when inspecting selections in your browser s developer tools 0 data shows the data bound to the inspected element document body data 42 The D3 idiomatic equivalent is to select the body and call datum d3 select body datum 42 If we now append an element to the body the child automatically inherits data from the parent d3 select body datum 42 append h1 And that brings us to the last method of binding data the mysterious join But before we can achieve enlightenment we must answer a more existential question What is Data Data in D3 can be any array of values For example an array of numbers var numbers 4 5 18 23 42 Or an array of objects One of Scott Murray s many tutorials covers common types of data in JavaScript var letters name A frequency 08167 name B frequency 01492 name C frequency 02780 name D frequency 04253 name E frequency 12702 Even an array of arrays var matrix 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 We can mirror the visual representation of selections to represent data Here s a plain array of five numbers Just as selection style takes either a constant string to define a uniform style property e g red for every selected element or a function to compute a dynamic style per element function d return d color selection data can accept either a constant value or a function However unlike the other selection methods selection data defines data per group rather than per element data is expressed as an array of values for the group or a function that returns such an array Thus a grouped selection has correspondingly grouped data Since there are four groups in the selection this data function is invoked four times and returns four arrays one per invocation Each returned array here also happens to contain four values but returned arrays may vary in length depending on data The blue lines in the diagram indicate that the data function returns the linked array Your data function is passed the datum of the

    Original URL path: https://bost.ocks.org/mike/selection/ (2016-04-30)
    Open archived version from archive

  • Why Use Make
    uncomfortable at first but it has advantages Unlike a linear script a dependency graph is flexible and modular for example you can augment the makefile to derive multiple shapefiles from the same zip archive without repeated downloads Capturing dependencies also begets efficiency you can remake generated files with only minimal effort when anything changes A well designed makefile allows you to iterate quickly while keeping generated files consistent and up to date The Syntax Isn t Pretty The ugly side of Make is its syntax and complexity the full manual is a whopping 183 pages Fortunately you can ignore most of this and start with explicit rules of the following form targetfile sourcefile command Here targetfile is the file you want to generate sourcefile is the file it depends on is derived from and command is something you run on the terminal to generate the target file These terms generalize a source file can itself be a generated file in turn dependent on other source files there can be multiple source files or zero source files and a command can be a sequence of commands or a complex script that you invoke In Make parlance source files are referred to as prerequisites while target files are simply targets Here s the rule to download the zip archive from the Census Bureau counties zip curl o counties zip http www2 census gov geo tiger GENZ2010 gz 2010 us 050 00 20m zip Put this code in a file called Makefile and then run make from the same directory Note use tabs rather than spaces to indent the commands in your makefile Otherwise Make will crash with a cryptic error If it worked you should see a downloaded counties zip in the directory You can approximate URL dependencies by checking the Last Modified header via curl I This first rule has no dependencies because it s the first step in the workflow or equivalently a leaf node in the dependency graph Although the zip file depends on the Census Bureau s website and thus can change Make has no native facility for checking if the contents of a URL have changed and thus a makefile cannot specify a URL as a prerequisite As a result the counties zip file will only be downloaded if it does not yet exist If the Census Bureau releases new cartographic boundaries you ll need to delete the previously downloaded zip file before running make The second rule for creating the shapefile now has a prerequisite the zip archive I preserved the Census Bureau s original verbose file name gz 2010 us 050 00 20m You could instead rename files using parameter expansion gz 2010 us 050 00 20m shp counties zip unzip counties zip touch gz 2010 us 050 00 20m shp This rule also has two commands First unzip expands the zip archive producing the desired shapefile and its related files Second touch sets the modification date of the shapefile to the current time The

    Original URL path: https://bost.ocks.org/mike/make/ (2016-04-30)
    Open archived version from archive

  • Let’s Make a Map
    style CSS goes here style body script src d3js org d3 v3 min js charset utf 8 script script src d3js org topojson v1 min js script script JavaScript goes here script Then fire up a local web server to view your example I use http server but any server will do A web server is needed to skirt security restrictions loading data out of the local file system http server p 8008 If you visit http localhost 8008 you should now see a glorious blank page View source step 1 html Probably not the excitement you were hoping for But we can change that pretty quickly Inside the main script tag where it says JavaScript goes here add a call to d3 json to load the TopoJSON file d3 json uk json function error uk if error return console error error console log uk Now if you peek at your JavaScript console you should see a topology object that represents the administrative boundaries and populated places of the United Kingdom Displaying Polygons There are a variety of ways to render two dimensional geometry in a browser but the two main standards are SVG and Canvas D3 3 0 supports both We ll use SVG for this example because you can style SVG via CSS and declarative styling is easier To create the root SVG element You could instead declare the SVG element in HTML but then you d need to pull the width and height out of the DOM var width 960 height 1160 var svg d3 select body append svg attr width width attr height height I recommend doing this at the top of the main script rather than inside the d3 json callback That s because d3 json is asynchronous the rest of the page will render while we wait for the TopoJSON file to download Creating the empty SVG root when the page first loads avoids distracting reflow when the geometry finally arrives We need two more things to render geography a projection and a path generator As its name implies the projection projects spherical coordinate to the Cartesian plane This is needed to display spherical geometry on a 2D screen you can skip this step if this is the future and you re using a 3D holographic display The path generator takes the projected 2D geometry and formats it appropriately for SVG or Canvas So make a map already Replace the code inside the d3 json callback like so d3 json uk json function error uk if error return console error error svg append path datum topojson feature uk uk objects subunits attr d d3 geo path projection d3 geo mercator You should now see a small black familiar speck View source step 2 html Lesser cartographers would now proclaim a job well done and go home for a beer But we re better than that so we ll polish a bit more before we throw in the towel Also it might help if I

    Original URL path: https://bost.ocks.org/mike/map/ (2016-04-30)
    Open archived version from archive

  • Working with Transitions
    For t 0 the interpolator returns the starting value for t 1 the interpolator returns the ending value and for values in between the interpolator returns a blending value For example to interpolate two numbers When rolling your own interpolator you may still be able to reuse some of D3 s built in interpolators function interpolateNumber a b return function t return a t b a When interpolating to or from zero some interpolated values may be very small JavaScript formats small numbers in exponential notation which unfortunately is not supported by CSS For example when transitioning opacity to fade in or out the number 0 0000001 is converted to the string 1e 7 and then ignored giving the default value of 1 To avoid distracting flicker start or end the transition at 1e 6 rather than 0 this is the smallest value not formatted in exponential notation Some Things Cannot Be Interpolated When modifying the DOM use selections for any changes that cannot be interpolated only use transitions for animation For example it is impossible to interpolate the creation of an element it either exists or it doesn t Furthermore in order to schedule a transition the element must exist and so element creation cannot be deferred to start Selection methods related to data joins data enter exit and creating elements append insert can therefore only be performed on selections When using transitions in conjunction with the general update pattern first perform the data join on selections using enter and exit Then derive transitions on each subselection as desired To perform a special transition on updating nodes derive a transition before appending to the enter selection var bar svg selectAll bar data data function d return d key bar enter append rect attr class bar initialize entering bars bar transition transition entering updating bars bar exit transition transition exiting bars remove For convenience there are a few exceptions to this rule You can transition remove to remove an element at the end of the transition likewise transition text sets the text content at the start of the transition without interpolating In the future transitions may support additional non interpolatable operations such as classed and html The Life of a Transition As with concurrent programming perhaps the trickiest aspect of transitions is that they happen over time rather than instantaneously The code does not proceed in a single straightforward path as when the page loads but as a complex sequence of recurring callbacks While you can safely ignore this complexity in many cases you must understand the rules which govern the evaluation of transitions if you want to harness their full power A useful mnemonic is that transitions are conceived born live and die But perhaps that takes the metaphor too literally Transitions have a four phase life cycle The transition is scheduled The transition starts The transition runs The transition ends This is a new feature in D3 3 0 older versions of D3 deferred computing ending values until

    Original URL path: https://bost.ocks.org/mike/transition/ (2016-04-30)
    Open archived version from archive

  • Drought during Month
    on crops but this was a fun animation we made to sanity check parsing drought data NOAA publishes monthly values for the Palmer Drought Severity Index going all the way back to 1895 Dark purple represents extreme drought while dark

    Original URL path: https://bost.ocks.org/mike/drought/ (2016-04-30)
    Open archived version from archive



  •