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".


  • (No additional info available in detailed archive for this subpage)
    Original URL path: (2016-04-30)


  • Mike Bostock
    Buck June 9 2013 For Example May 25 2013 Across U S Companies Tax Rates Vary Greatly April 26 2013 How Selections Work April 25 2013 N F L Draft How Good Are Teams at Picking the Best April 8 2013 China Still Dominates but Some Manufacturers Look Elsewhere March 2 2013 Increased Border Enforcement With Varying Results February 23 2013 Why Use Make February 20 2013 Among the Oscar Contenders a Host of Connections January 3 2013 A Chicago Divided by Killings December 30 2012 Let s Make a Map November 29 2012 How the Tax Burden Has Changed November 11 2012 Counties Blue and Red Moving Right and Left November 7 2012 How Obama Won Re election November 2 2012 512 Paths to the White House October 30 2012 Wind Speeds Along Hurricane Sandy s Path October 24 2012 Working with Transitions October 15 2012 Over the Decades How States Have Shifted September 18 2012 A Faded Piece of Papyrus Refers to Jesus Wife September 14 2012 How the Chicago Public School District Compares September 6 2012 At the National Conventions the Words They Used September 4 2012 At the Democratic Convention the Words Being Used August 28 2012 At the Republican Convention the Words Being Used August 24 2012 Drought during Month August 24 2012 Drought Extends Crops Wither August 10 2012 Drought and Deluge in the Lower 48 June 21 2012 Fisheye Distortion June 19 2012 D3 Leaflet June 10 2012 Zoomable Treemaps June 1 2012 Line Simplification May 22 2012 Sankey Diagrams May 16 2012 Object Constancy April 8 2012 Nested Selections March 18 2012 Hive Plots March 13 2012 The Wealth Health of Nations February 27 2012 Towards Reusable Charts February 5 2012 Thinking with Joins January 21 2012 Will It Shuffle January 19 2012 Path Transitions January 14 2012 Fisher Yates Shuffle January 12 2012 Les Misérables Co occurrence January 9 2012 Uber Rides by Neighborhood Examples In addition to the graphics and articles listed above I have posted almost a thousand examples on bl ocks org mbostock Peruse them to learn D3 or for visual inspiration Talks Occasionally I stand in front of a room of people and by flapping my lips or waving my arms attempt to communicate something of interest These awkward moments are sometimes captured as moving images and sound for future study Q A September 8 2015 Reddit AMA Video September 8 2014 FOSS4G The Toolmaker s Guide Video June 11 2014 Eyeo Visualizing Algorithms Video April 24 2014 OpenVis Design is a Search Problem Video June 6 2013 Eyeo For Example Slides Video May 2 2012 Time Series Visualization with Cubism js Slides March 5 2012 VIZBI D3 Workshop Slides Video November 16 2011 W3C Conf Visualizing Data with Web Standards Slides October 18 2011 SVG Open D3 Keynote Slides Video September 21 2011 Trulia Meetup Use the Force Publications As part of my PhD studies at the Stanford Vis Group I published several papers with Jeffrey

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

  • Let’s Make a (D3) Plugin
    do use an ellipsis as a placeholder Effective documentation is a topic for another day but try to convey at least one compelling common use case so that readers can quickly grasp your plugin s raison d être Adopting the standard format for the API reference will also help people learn how to use your plugin more quickly If your plugin depends on other D3 modules specify a dependencies hash in the package json using the name of the module as the key and the acceptable versions as the value For example dependencies d3 path 0 1 2 Alternatively use npm install save to install a module and add it to the package json automatically This is nice because it will always pick the latest published version As the last step of specifying dependencies find the rollup command in the pretest script in the package json and add a g argument to enumerate the names of each dependant module For example The g step is only necessary because Rollup by default generates globals of the form d3Path instead of d3 path This step may go away in the future rollup g d3 path d3 path Now let s get to the code Edit the Code The top level index js file specifies the symbols that your module exports the public API In the starter file that s a single symbol named foo export default as foo from src foo Everything you export from this top level file should be documented in your API reference in the README See d3 timer and d3 random for more examples You can put arbitrary code in your index file too as in d3 time and d3 format but keep things simple if you can The src folder contains the module implementation Typically there s one source file for each symbol you export but just as often a source file exports multiple symbols or contains code that s private to the module That s all up to you For example here s src foo js from the starter template export default function return 42 Note that these import and export statements are the only new langauge feature adopted by D3 modules While you can use other language features and a transpiler say Babel I recommend limiting yourself D3 s module pattern is intended to maximize compatibility with other D3 modules and so tends to be conservative The imports and exports are processed by Rollup to produce the bundle but Rollup does not transpile any other language features As you implement your plugin please update the tests for the public API accordingly By convention D3 modules use Substack s Tape as a testing harness And we use JSDOM for DOM testing You re free to use something else but it s nice if modules are consistent To verify that everything is setup correctly install all dependencies run the tests and build generated files like so npm install You should see the tests pass in green and

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

  • How To Scroll
    mobile thanks to touch events although it d still be nice to have a web standard for swiping It s extraordinarily sensitive Even the smallest wheel event scrolling a single pixel is interpreted as scrolling an entire window height an effective magnification of three orders of magnitude Swipe gestures that occur during the animation of a previous swipe are either dropped on the floor or queued until the animation finishes This makes scrolling feel laggy or unresponsive and is exacerbated by sensitivity there s no way to interrupt an accidental scroll You cannot control the speed of the swipe animations frustrating readers that want to scroll faster or slower and disabling rapid visual scanning of the entire page Even a quick peek ahead requires sitting through two animations You lose the scroll bar so you can no longer click and drag the scroll thumb for direct manipulation of the viewport or click the scroll bar to jump to an arbitrary point And you lose a visual representation of the currently visible region of the page The custom replacement tiny vertical dots restores only a subset of this functionality You lose standard keyboard controls see 5 You lose rubber banding at the top and bottom of the page abandoning helpful visual feedback and further making the page feel unresponsive The second approach retains standard scrolling behavior but alters the display based on the current viewport through the use of position fixed elements The page is divided vertically into screens with scroll based thresholds to trigger transition between screens Transitions between screens may be time based with an instantaneous trigger such as a 250ms cross fade when pageYOffset crosses 1200px or positioned based within a transitionary region such as a cross fade from zero opacity at 1100px to full opacity at 1200px Position based transitions automatically adjust speed to match how the reader scrolls however triggered time based transitions avoid the possibility of sitting in a transition indefinitely which can be unsettling Importantly even when time based transitions are used the reader can still interrupt the transition and has full control over the viewport As you may have guessed I am a strong proponent of the second approach It preserves direct manipulation whereas the first approach feels indirect and detached I would rather scroll the page myself than hand wave a butler to advance the page on my behalf The first school seems to value the purity of the designer s aesthetics over the user s experience Rapid incremental reversible scrolls are more usable than slow animated swipes Swipe gestures may become viable when touch events are supported on desktop and swipes can be detected reliably But don t take my word for it you decide Two well known examples of the first school are Huge s home page and Apple s Mac Pro page Two examples of the second school with position based scroll transitions are A Game of Shark and Minnow and our preview of Ted Ligety for Sochi 2014

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

  • Visualizing Algorithms
    description has its place in unambiguous documentation visualization can make intuitive understanding more accessible Debugging Have you ever implemented an algorithm based on formal description It can be hard Being able to see what your code is doing can boost productivity Visualization does not supplant the need for tests but tests are useful primarily for detecting failure and not explaining it Visualization can also discover unexpected behavior in your implementation even when the output looks correct See Bret Victor s Learnable Programming and Inventing on Principle for excellent related work Learning Even if you just want to learn for yourself visualization can be a great way to gain deep understanding Teaching is one of the most effective ways of learning and implementing a visualization is like teaching yourself I find it easier to remember an algorithm intuitively having seen it than to memorize code where I am bound to forget small but essential details Shuffling Shuffling is the process of rearranging an array of elements randomly For example you might shuffle a deck of cards before dealing a poker game A good shuffling algorithm is unbiased where every ordering is equally likely The Fisher Yates shuffle is an optimal shuffling algorithm Not only is it unbiased but it runs in linear time uses constant space and is easy to implement function shuffle array var n array length t i while n i Math random n 0 0 i Above is the code and below is a visual explanation For a more detailed explanation of this algorithm see my post on the Fisher Yates shuffle Each line represents a number Small numbers lean left and large numbers lean right Note that you can shuffle an array of anything not just numbers but this visual encoding is useful for showing the order of elements It is inspired by Robert Sedgwick s sorting visualizations in Algorithms in C The algorithm splits the array into two parts the right side of the array in black is the shuffled section while the left side of the array in gray contains elements remaining to be shuffled At each step it picks a random element from the left and moves it to the right thereby expanding the shuffled section by one The original order on the left does not need to be preserved so to make room for the new element in the shuffled section the algorithm can simply swap the element into place Eventually all elements are shuffled and the algorithm terminates If Fisher Yates is a good algorithm what does a bad algorithm look like Here s one DON T DO THIS function shuffle array return array sort function a b return Math random 5 ಠ ಠ This approach uses sorting to shuffle by specifying a random comparator function A comparator defines the order of elements It takes arguments a and b two elements from the array to compare and returns a value less than zero if a is less than b a value greater than zero if a is greater than b or zero if a and b are equal The comparator is invoked repeatedly during sorting If you don t specify a comparator to array sort elements are ordered lexicographically Here the comparator returns a random number between 5 and 5 The assumption is that this defines a random order so sorting will jumble the elements randomly and perform a good shuffle Unfortunately this assumption is flawed A random pairwise order for any two elements does not establish a random order for a set of elements A comparator must obey transitivity if a b and b c then a c But the random comparator returns a random value violating transitivity and causing the behavior of array sort to be undefined You might get lucky or you might not How bad is it We can try to answer this question by visualizing the output Another reason this algorithm is bad is that sorting takes O n lg n time making it significantly slower than Fisher Yates which takes O n But speed is less damning than bias This may look random so you might be tempted to conclude that random comparator shuffle is adequate and dismiss concerns of bias as pedantic But looks can be misleading There are many things that appear random to the human eye but are substantially non random This deception demonstrates that visualization is not a magic wand Showing a single run of the algorithm does not effectively assess the quality of its randomness We must instead carefully design a visualization that addresses the specific question at hand what is the algorithm s bias To show bias we must first define it One definition is based on the probability that an array element at index i prior to shuffling will be at index j after shuffling If the algorithm is unbiased every element has equal probability of ending up at every index and thus the probability for all i and j is the same 1 n where n is the number of elements Computing these probabilities analytically is difficult since it depends on knowing the exact sorting algorithm used But computing them empirically is easy we simply shuffle thousands of times and count the number of occurrences of element i at index j An effective display for this matrix of probabilities is a matrix diagram SHUFFLE BIAS column index before shuffle row index after shuffle green positive bias red negative bias The column horizontal position of the matrix represents the index of the element prior to shuffling while the row vertical position represents the index of the element after shuffling Color encodes probability green cells indicate positive bias where the element occurs more frequently than we would expect for an unbiased algorithm likewise red cells indicate negative bias where it occurs less frequently than expected Random comparator shuffle in Chrome shown above is surprisingly mediocre Parts of the array are only weakly biased However it exhibits a strong positive bias below the diagonal which indicates a tendency to push elements from index i to i 1 or i 2 There is also strange behavior for the first middle and last row which might be a consequence of Chrome using median of three quicksort The unbiased Fisher Yates algorithm looks like this No patterns are visible in this matrix other than a small amount of noise due to empirical measurement That noise could be reduced if desired by taking additional measurements The behavior of random comparator shuffle is heavily dependent on your browser Different browsers use different sorting algorithms and different sorting algorithms behave very differently with broken random comparators Here s random comparator shuffle on Firefox For an interactive version of these matrix diagrams to test alternative shuffling strategies see Will It Shuffle This is egregiously biased The resulting array is often barely shuffled as shown by the strong green diagonal in this matrix This does not mean that Chrome s sort is somehow better than Firefox s it simply means you should never use random comparator shuffle Random comparators are fundamentally broken Sorting Sorting is the inverse of shuffling it creates order from disorder rather than vice versa This makes sorting a harder problem with diverse solutions designed for different trade offs and constraints One of the most well known sorting algorithms is quicksort Quicksort Quicksort first partitions the array into two parts by picking a pivot The left part contains all elements less than the pivot while the right part contains all elements greater than the pivot After the array is partitioned quicksort recurses into the left and right parts When a part contains only a single element recursion stops The partition operation makes a single pass over the active part of the array Similar to how the Fisher Yates shuffle incrementally builds the shuffled section by swapping elements the partition operation builds the lesser left and greater right parts of the subarray incrementally As each element is visited if it is less than the pivot it is swapped into the lesser part if it is greater than the pivot the partition operation moves on to the next element Here s the code function quicksort array left right if left 1 pivot partition array left right pivot quicksort array left pivot quicksort array pivot 1 right function partition array left right pivot var pivotValue array pivot swap array pivot right for var i left i There are many variations of quicksort The one shown above is one of the simplest and slowest This variation is useful for teaching but in practice more elaborate implementations are used for better performance A common improvement is median of three pivot selection where the median of the first middle and last elements is used as the pivot This tends to choose a pivot closer to the true median resulting in similarly sized left and right parts and shallower recursion Another optimization is switching from quicksort to insertion sort for small parts of the array which can be faster due to the overhead of function calls A particularly clever variation is Yaroslavskiy s dual pivot quicksort which partitions the array into three parts rather than two This is the default sorting algorithm in Java and Dart The sort and shuffle animations above have the nice property that time is mapped to time we can simply watch how the algorithm proceeds But while intuitive animation can be frustrating to watch especially if we want to focus on an occasional weirdness in the algorithm s behavior Animations also rely heavily on our memory to observe patterns in behavior While animations are improved by controls to pause and scrub time static displays that show everything at once can be even more effective The eye scans faster than the hand A simple way of turning an animation into a static display is to pick key frames from the animation and display those sequentially like a comic strip If we then remove redundant information across key frames we use space more efficiently A denser display may require more study to understand but is faster to scan since the eye travels less Below each row shows the state of the array prior to recursion The first row is the initial state of the array the second row is the array after the first partition operation the third row is after the first partition s left and right parts are again partitioned etc In effect this is breadth first quicksort where the partition operation on both left and right proceeds in parallel Quicksort As before the pivots for each partition operation are highlighted in red Notice that the pivots turn gray at the next level of recursion after the partition operation completes the associated pivot is in its final sorted position The total depth of the display the maximum depth of recursion gives a sense of how efficiently quicksort performed It depends heavily on input and pivot choice Another static display of quicksort less dense but perhaps easier to read represents each element as a colored thread and shows each sequential swap This form is inspired by Aldo Cortesi s sorting visualizations Smaller values are lighter and larger values are darker At the start of each partition the pivot is moved to the end the right of the active subarray Partitioning then proceeds from left to right At each step a new element is added either of the set of lesser values in which case a swap occurs or to the set of greater values in which case no swap occurs When a swap occurs the left most value greater than the pivot is moved to the right so as to make room on the left for the new lesser value Thus notice that in all swap operations only values darker than the pivot move right and only values lighter than the pivot move left When the partition operation has visited all elements in the array the pivot is placed in its final position between the two parts Then the algorithm recurses into the left part followed by the right part far below This visualization doesn t show the state of the stack so it can appear to jump around arbitrarily due to the nature of recursion Still you can typically see when a partition operation finishes due to the characteristic movement of the pivot to the end of the active subarray Quicksort You ve now seen three different visual representations of the same algorithm an animation a dense static display and a sparse static display Each form has strengths and weaknesses Animations are fun to watch but static visualizations allow close inspection without being rushed Sparse displays may be easier to understand but dense displays show the macro view of the algorithm s behavior in addition to its details Before we move on let s contrast quicksort with another well known sorting algorithm mergesort function mergesort array var n array length a0 array a1 new Array n for var m 1 m end a0 i0 Again above is the code and below is an animation Mergesort As you ve likely surmised from either the code or the animation mergesort takes a very different approach to sorting than quicksort Unlike quicksort which operates in place by performing swaps mergesort requires an extra copy of the array This extra space is used to merge sorted subarrays combining the elements from pairs of subarrays while preserving order Since mergesort performs copies instead of swaps we must modify the animation accordingly or risk misleading readers Mergesort works from the bottom up Initially it merges subarrays of size one since these are trivially sorted Each adjacent subarray at first just a pair of elements is merged into a sorted subarray of size two using the extra array Then each adjacent sorted subarray of size two is merged into a sorted subarray of size four After each pass over the whole array mergesort doubles the size of the sorted subarrays eight sixteen and so on Eventually this doubling merges the entire array and the algorithm terminates Because mergesort performs repeated passes over the array rather than recursing like quicksort and because each pass doubles the size of sorted subarrays regardless of input it is easier to design a static display We simply show the state of the array after each pass Mergesort Let s again take a moment to consider what we ve seen The goal here is to study the behavior of an algorithm rather than a specific dataset Yet there is still data necessarily the data is derived from the execution of the algorithm And this means we can use the type of derived data to classify algorithm visualizations Level 0 black box The simplest class just shows the output This does not explain the algorithm s operation but it can still verify correctness And by treating the algorithm as a black box you can more easily compare outputs of different algorithms Black box visualizations can also be combined with deeper analysis of output such as the shuffle bias matrix diagram shown above Level 1 gray box Many algorithms though not all build up output incrementally By visualizing the intermediate output as it develops we start to see how the algorithm works This explains more without introducing new abstraction since the intermediate and final output share the same structure Yet this type of visualization can raise more questions than it answers since it offers no explanation as to why the algorithm does what it does Level 2 white box To answer why questions white box visualizations expose the internal state of the algorithm in addition to its intermediate output This type has the greatest potential to explain but also the highest burden on the reader as the meaning and purpose of internal state must be clearly described There is a risk that the additional complexity will overwhelm the reader layering information may make the graphic more accessible Lastly since internal state is highly dependent on the specific algorithm this type of visualization is often unsuitable for comparing algorithms There s also the practical matter of implementing algorithm visualizations Typically you can t just run code as is you must instrument it to capture state for visualization View source on this page for examples You may even need to interleave execution with visualization which is particularly challenging for recursive algorithms that capture state on the stack Language parsers such as Esprima may facilitate algorithm visualization through code instrumentation cleanly separating execution code from visualization code Maze Generation The last problem we ll look at is maze generation All algorithms in this section generate a spanning tree of a two dimensional rectangular grid This means there are no loops and there is a unique path from the root in the bottom left corner to every other cell in the maze I apologize for the esoteric subject I don t know enough to say why these algorithms are useful beyond simple games and possibly something about electrical networks But even so they are fascinating from a visualization perspective because they solve the same highly constrained problem in wildly different ways And they re just fun to watch Random traversal The random traversal algorithm initializes the first cell of the maze in the bottom left corner The algorithm then tracks all possible ways by which the maze could be extended shown in red At each step one of these possible extensions is picked randomly and the maze is extended as long as this does not reconnect it with another part of the maze Like Bridon s Poisson disc sampling algorithm random traversal maintains a frontier and randomly selects from that frontier to expand Both algorithms thus appear to grow organically like a fungus Randomized depth first traversal follows a very different pattern Randomized depth first traversal Rather than picking a new random passage each time this algorithm always extends the deepest passage the one with the longest

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

  • Three Little Circles
    cx 40 cy 60 r 5 656854249492381 style fill steelblue circle circle cx 80 cy 60 r 7 54983443527075 style fill steelblue circle circle cx 120 cy 60 r 10 583005244258363 style fill steelblue circle svg There s a second optional argument to each function you can also use the index of the element within its selection The index is often useful for positioning elements sequentially Again by convention this is often referred to as i For example circle attr cx function d i return i 100 30 svg width 720 height 120 circle cx 30 cy 60 r 5 656854249492381 style fill steelblue circle circle cx 130 cy 60 r 7 54983443527075 style fill steelblue circle circle cx 230 cy 60 r 10 583005244258363 style fill steelblue circle svg Note that in SVG the origin is in the top left corner Entering Elements What if we had four numbers to display rather than three We wouldn t have enough circles and we would need to create more elements to represent our data You can append new nodes manually but a more powerful alternative is the enter selection computed by a data join When joining data to elements D3 puts any leftover data or equivalently missing elements in the enter selection With only three circles a fourth number would be put in the enter selection while the other three numbers are returned directly in the update selection by selection data By appending to the enter selection we can create new circles for any missing data The new circles will be appended to the element defined by parent selection So we select the svg element first then select all circle elements and then join them to data var svg d3 select svg var circle svg selectAll circle data 32 57 112 293 var circleEnter circle enter append circle Entering elements are already bound to the data so we can use data to compute attributes and styles as well as set constant properties circleEnter attr cy 60 circleEnter attr cx function d i return i 100 30 circleEnter attr r function d return Math sqrt d Now we have four circles svg width 720 height 120 circle cx 30 cy 60 r 5 656854249492381 style fill steelblue circle circle cx 130 cy 60 r 7 54983443527075 style fill steelblue circle circle cx 230 cy 60 r 10 583005244258363 style fill steelblue circle circle cx 330 cy 60 r 17 11724276862369 style fill steelblue circle svg Taking this to the logical extreme then what if we have no existing elements such as with an empty page Then we re joining data to an empty selection and all data ends up in enter This pattern is so common you ll often see the selectAll data enter append methods called sequentially one immediately after the other Despite it being common keep in mind that this is just one special case of a data join svg selectAll circle data 32 57 112 293 enter append circle

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

  • Let’s Make a Bubble Map
    we re just displaying the county boundaries so far using topojson mesh We still have a bit of work to do before we can draw population bubbles Finding Data The next task is to fetch the data we want to visualize population estimates by county Sometimes you may find that data conveniently baked into your shapefile but here we ll need to return to the U S Census Bureau and gather the requisite table from the American Community Survey ACS using the American FactFinder The ACS publishes 1 year 3 year and 5 year estimates The 5 year estimates are the most accurate and are available in smaller geographic subdivisions such as census tracts If you care more about recency than accuracy use the 3 or 1 year estimates instead Here are the approximately twenty steps required to download a CSV Go to factfinder2 census gov Find where it says American Community Survey and click get data Click the blue Geographies button on the left In the pop up select County 050 in the geographic type menu Select All Counties within United States in the geographic areas box Click the ADD TO YOUR SELECTIONS button Click CLOSE to dismiss the pop up Click the blue Topics button on the left In the pop up expand the People submenu Expand the Basic Count Estimate submenu Click Population Total Click CLOSE to dismiss the pop up In the table click on the most recent ACS 5 year estimate named TOTAL POPULATION On the next page click the Download link under Actions In the pop up click OK Wait for it to build your file When it s ready click DOWNLOAD Finally expand the downloaded zip file ACS 12 5YR B01003 zip Did you know The American FactFinder2 cost 33 3 million and was built by IBM U S Federal If you would prefer this as a two minute instructional video I recently learned that the Census Bureau has an API However it requires an API key so I haven t tried it yet The API supports stateless GET requests so it should be easy to incorporate into the Makefile If you ve tried it let me know how it worked out An eminently more usable alternative to FactFinder is censusreporter org a Knight News Challenge funder project with a convenient autocomplete interface and a robust API Here is a direct link to download the latest ACS total population estimate by county Note however that the column headers for this CSV are slightly different than the ones from FactFinder you must either edit the file or the Makefile rules accordingly If you want to experience the FactFinder vicariously you may also instead download my copy However I recommend that you prefer data from primary sources whenever possible as this ensures the data s accuracy Merging Data The downloaded ACS 12 5YR B01003 with ann csv is slightly unusual in that it contains two header lines Normally a CSV file only contains at most one header line defining the names of the columns this is the format that d3 csv and TopoJSON expects Open the downloaded CSV in your text editor and delete the first of the two header lines The first few lines should look like this Id Id2 Geography Estimate Total Margin of Error Total 0500000US01001 01001 Autauga County Alabama 54590 0500000US01003 01003 Baldwin County Alabama 183226 0500000US01005 01005 Barbour County Alabama 27469 Now we can use TopoJSON s external properties feature to join the shapefile of counties with the CSV of population estimates making additional properties available in the output TopoJSON This flag works similar to a join in a relational database Using the ID property as a primary key we assign each row in the CSV file to the corresponding feature in the shapefile One frequent complication is that the external properties do not use the same ID property name as the shapefile Here the CSV file uses the name Id2 while the shapefile uses STATE and COUNTY We could use the longer Id and GEO ID properties but we d prefer to use the shorter identifier here without the redundant leading 0500000US To address these inconsistencies the id property argument accepts a comma separated list of JavaScript expressions to specify how the ID property should be computed For the shapefile we ll use the expression STATE COUNTY to concatenate those two properties while for the CSV we ll use Id2 We can also use JavaScript expressions to define the properties we want to include in the generated TopoJSON Here we ll map the Geography column from the CSV to the name property and the Estimate Total column to the population property The latter requires special syntax because the column name isn t a valid JavaScript identifier Also we want it to be a number Modifying our Makefile slightly build counties json build gz 2010 us 050 00 20m shp ACS 12 5YR B01003 with ann csv node modules bin topojson o id property STATE COUNTY Id2 external properties ACS 12 5YR B01003 with ann csv properties name Geography properties population d properties Estimate Total projection width 960 height 600 d3 geo albersUsa scale 1280 translate width 2 height 2 simplify 5 counties Merging Boundaries One subtle detail you may not have noticed in the final bubble map is that it displays state boundaries rather than county boundaries This reduces visual noise each county has a corresponding bubble while the state boundary lines provide additional geographic context We can compute the state boundaries without downloading another shapefile because TopoJSON is a topological format The following rule merges or dissolves counties within the same state producing a new states layer in the output TopoJSON file build states json build counties json node modules bin topojson merge o in object counties out object states key d id substring 0 2 The resulting state mesh A similar rule can compute the national boundary by merging states us json build states json node modules

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

  • Let’s Make a Block
    Text from the terminal create one like so ln s Applications Sublime Text 2 app Contents SharedSupport bin subl usr local bin subl Now edit the contents of the file so they look like this The order of lines is important the earlier lines take priority If you install something with NPM or Homebrew you want it to take priority over something bundled with your OS The latter are often out of date usr local share npm bin usr local bin usr bin bin usr sbin sbin Once you ve made your changes and saved close and reopen the terminal to pick up the new PATH Develop In the terminal make a new folder for your example and then cd into that folder mkdir example cd example Next make an empty file in this folder for your example code and open the entire thing in Sublime touch index html subl In Sublime Text you should now see an empty window Sublime Text has a bug where if you open an empty folder saving a new file won t default to this folder Opening a folder with at least one file even if it s empty avoids this bug Hence the touch If you want another file say a README or Makefile use N to create it and S to save it it will automatically default to the right folder Hit T Go to File and start typing index html As soon as index html highlighted stop typing and hit return to open it Paste in the following contents and save S DOCTYPE html meta charset utf 8 Hello world Back in the terminal fire up the web server so that you can preview your code in a web browser http server The ampersand tells the terminal to run the web server in the background This means you can continue to use the terminal to run other commands When you re all done you can bring it back to the foreground by running fg and then interrupt it with C control C Or just close the terminal window With http server running visit localhost 8080 in your browser and refresh whenever you make changes Iterate as many times as you like to develop your example bouncing between your text editor and web browser Publish Now you need Gistup another Node program to create the gist from the terminal To install npm install g gistup You can give your gist a description using the m option such as gistup m Hello World You can also edit the description later by visiting the gist in a web browser Use gistup i for interactive mode Next to create the gist from the files in the current folder gistup When gistup completes successfully it will open the new gist in your web browser Running gistup for the first time requires creating a personal access token so that you can post to the GitHub API from the terminal it also requires setting up SSH keys so

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



  •