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".
  • Cubism
    there s no free lunch think it through There are few hard rules but research has established many best practices for effective visualization design For a good introduction see Tamara Munzner s talk on Visualization Principles and the books of Bertin and Tufte Aspect ratios matter And now what not to do Given the noisiness of these metrics the aspect ratio on this stacked area chart is too tall Banking to 45º would improve slope differentiation Stacking makes middle layers hard to read Stacked graphs are acceptable for certain uses but it s easier to perceive the bottom most layer and the sum than it is to observe changes in the middle spikes in lower layers mask changes in those above Garish colors can be hard to see In addition to the aspect ratio the colors on this chart are abysmal Avoid fully saturated colors especially yellow on white When in doubt use ColorBrewer Chroma js is also useful for designing new color scales Load and render data incrementally Provide details on demand Allow panning zooming etc Make better use of modern browsers We ve come a long way since 1994 Modern browsers can generate dynamic graphics and fetch asynchronously using web standards Interaction can make dashboards much more powerful start with an overview then allow zoom and filter for closer inspection Horizon Charts Mirror Offset 1 Combine position and color to reduce vertical space Start with a standard area chart then mirror negative values in blue or offset them vertically Click the button above to increase the number of bands turning the area into a horizon Wow look at all those metrics Because they share a common x axis it s easier to spot coincident anomalies This is random data so it s not especially interesting but keep reading for better examples These charts show the percentage change of 19 technology stocks since December 2008 It s easy to spot similarities market events that affected multiple stocks Cubism js A small library not a system var context cubism context step 1e4 ten seconds size 1440 four hours cubism context Synchronize fetching and rendering The context coordinates Cubism s various components charts metrics axes etc Why a context Avoids distracting redraws async fetch sync render Per pixel resolution maximize data density With Cubism you specify the resolution of each pixel rather than the duration of the entire chart This guarantees optimal data density one metric value per pixel var graphite context graphite http example com context graphite Define a source for Graphite metrics This slide and the next show how to fetch metrics from Graphite you can also plug in other data sources var foo graphite metric sumSeries foo alias Foo graphite metric Fetch data from Graphite Given a data source such as Graphite you can create multiple metrics The alias method makes them human readable var horizon context horizon metric foo context horizon Visualize metrics as horizon charts You can visualize metrics as horizon charts or comparison charts or

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



  • jQuery pre code Selections are Arrays Use developer tools to select inspect modify and experiment select all circle elements var circle d3 selectAll circle set some attributes and styles circle attr cx 20 circle attr cy 12 circle attr r 24 circle style fill red The attr and style methods set attributes and styles respectively One thing to note numbers and other values are automatically coerced to strings when setting attributes and styles So you don t have to do that yourself which is nice and you can also use helper classes such as d3 rgb and d3 hsl select all circle elements and set some attributes and styles d3 selectAll circle attr cx 20 attr cy 12 attr r 24 style fill red Method chaining allows shorter and more readable code selection append Create new elements append and select select the body element var body d3 select body add an h1 element var h1 body append h1 h1 text Hello With one element selected adds one element select all section elements var section d3 selectAll section add an h1 element to each var h1 section append h1 h1 text Hello With many elements selected adds one element to each var h1 d3 selectAll section style background steelblue append h1 text Hello Use caution with method chaining append returns a new selection With method chaining I normally use four spaces to indent However I use two spaces for operations that change the selection such as append This causes operations that change the context to stick out In this snippet the entire expression evaluates to the appended h1 elements even though we started by selecting section elements Add many elements No single operation this brings us to our next topic Data Data are Arrays You can represent data however you like in JavaScript Selections are arrays and data are arrays Coincidence Nope A bar chart perhaps var data 1 1 2 3 5 8 Data can be numbers If you want to be fancy you can call an array of numbers a univariate dataset bar chart html A scatterplot perhaps var data x 10 0 y 9 14 x 8 0 y 8 14 x 13 0 y 8 74 x 9 0 y 8 77 x 11 0 y 9 26 Data can be objects If you want to be fancy you can call an array of objects a multivariate dataset dot chart html Nerd cred if you recognize this Data Elements Use data to create multiple elements D3 doesn t provide a single method for creating multiple elements instead it provides a pattern for managing the mapping from data to elements The way to create elements from scratch is a special case of the more generalized form svg selectAll circle data data enter append circle attr cx x attr cy y attr r 2 5 We want the selection circle to correspond to data This common snippet creates new elements from data The first line may be surprising why select circle elements if you know they don t exist Well you re telling D3 that you want them to correspond to data This parsimonious approach means that when you need to handle update and exit in the future for your interactive or dynamic visualizations it s a simple extension of a pattern you already know var circle svg selectAll circle data data The data method computes the join defining enter and exit The data method does all the work The enter and exit methods just return the subselections computed in the join var circle svg selectAll circle data data circle enter append circle Appending to the enter selection creates the missing elements The append method on enter selections is special it still creates one new element per selected element but it adds them to the parent node here the SVG element var circle svg selectAll circle data data circle enter append circle attr cx x attr cy y attr r 2 5 The new elements are bound to data so we can compute attributes X and y here refer to accessor functions such as function x d return d x I couldn t fit them on the slide I commonly use anonymous functions to compute attributes from data Enter Update Exit Thinking with Joins I wrote a tutorial on joins recently which is hopefully my best attempt yet at explaining D3 s data join The data join is likely the hardest concept of D3 to grasp but it s a powerful way of manipulating the DOM Enter New data for which there were no existing elements var circle svg selectAll circle data data enter append circle attr cx x attr cy y attr r 2 5 When initializing you might ignore update and exit This is the same code snippet as before In effect we ve simplified the general pattern by assuming there are no updating or exiting elements Update New data that was joined successfully to an existing element var circle svg selectAll circle data data attr cx x attr cy y attr r 2 5 When updating you might ignore enter and exit Exit Existing elements for which there were no new data I didn t include a code snippet here but typically you just call selection remove on exit You can also create an exit transition so that elements animate before removal Enter Update Entering nodes are added to update on append OK one more special feature of the append method on enter selections This makes it easier for you to operate on entering and updating elements simultaneously without needing to reselect after computing the data join This reduces code duplication Key Function You can control the join by default the join is by index You can ignore key functions if you are creating static visualizations you usually need a key function only if you are doing transitions and want to maintain object constancy A scatterplot perhaps var data name Alice x 10 0 y 9 14 name Bob x 8 0 y 8 14 name Carol x 13 0 y 8 74 name Dave x 9 0 y 8 77 name Edith x 11 0 y 9 26 If needed data should have a unique key for joining function key d return d name var circle svg selectAll circle data data key attr cx x attr cy y attr r 2 5 The key function returns a unique string for each datum Loading Data D3 provides several convenience routines using XMLHttpRequest Loading data isn t core feature of D3 per se but since it s commonly needed there are a few built in convenience methods CSV Comma Separated Values d3 csv symbol date price S P 500 Jan 2000 1394 46 S P 500 Feb 2000 1366 42 S P 500 Mar 2000 1498 58 S P 500 Apr 2000 1452 43 S P 500 May 2000 1420 6 S P 500 Jun 2000 1454 6 S P 500 Jul 2000 1430 83 stocks csv var format d3 time format b Y d3 csv stocks csv function stocks stocks forEach function d d price d price d date format parse d date CSV is untyped so coercion from strings is required The array forEach method is a built in JavaScript method to iterate over all elements in an array here rows in the loaded CSV file area chart html JSON JavaScript Object Notation d3 json Use JSON rather than JSONP if you can JSONP is insecure and as often practiced synchronous For loading cross domain data use the Access Control Allow Origin header instead symbol S P 500 date Jan 2000 price 1394 46 symbol S P 500 date Feb 2000 price 1366 42 symbol S P 500 date Mar 2000 price 1498 58 symbol S P 500 date Apr 2000 price 1452 43 symbol S P 500 date May 2000 price 1420 6 symbol S P 500 date Jun 2000 price 1454 6 symbol S P 500 date Jul 2000 price 1430 83 symbol S P 500 date Aug 2000 price 1517 68 symbol S P 500 date Sep 2000 price 1436 51 symbol S P 500 date Oct 2000 price 1429 4 symbol S P 500 date Nov 2000 price 1314 95 symbol S P 500 date Dec 2000 price 1320 28 symbol S P 500 date Jan 2001 price 1366 01 stocks json var format d3 time format b Y d3 json stocks json function stocks stocks forEach function d d date format parse d date JSON is typed but you must still parse dates Another option is to represent dates as UNIX epoch milliseconds or ISO 8601 strings in which case you can use the Date constructor rather than a time format Data is Asynchronous Code that depends on data must be invoked via callback D3 doesn t provide any synchronous methods for loading data loading data asynchronously should give a better experience for your users since the browser won t stall while data is loading Data is Messy Data is rarely in the exact format needed for visualization This doesn t scratch the surface of the data cleaning problem For that see projects such as Google Refine and Stanford s Data Wrangler array filter map sort JavaScript has a number of useful built in array methods Deferring data transformations to the client often makes it easier for you to prototype visualizations rapidly you can change the data on the fly rather than needing to re run your data pipeline On the other hand when you want to share your visualization with the world it s a good idea to optimize your dataset for performance d3 nest keys values D3 also has a variety of data transform methods explore the API Scales Axes Scales Data Attributes Attributes and styles control position and appearance We use the data join to maintain the mapping from data to elements but what about the mapping from data to attributes We need to compute attributes from data to generate visual encodings position color etc Scales help with this Domain Range Scales are functions that map from data space to visual space Some scales can also go the other way and compute an inverse mapping from range to domain the scale invert method this is useful for interaction function x d return d 42 px Scales are convenient but optional you can roll your own The function x here is a linear scale But it s a pain to implement scales this way because you end up hard coding the scale factor e g 42 Quantitative Scales Map a continuous numeric domain to a continuous range var x d3 scale linear domain 12 24 range 0 720 x 16 240 A linear scale simply translates and scales The domain of a scale is the expected data values here from 12 to 24 while the range is the desired output values 0 is the left side of the chart and 720 is the right side of the chart Thus this scale implements a position encoding var x d3 scale sqrt domain 12 24 range 0 720 x 16 268 9056992603583 A sqrt or pow scale applies an exponential transform Sometimes you want to transform the data as part of the encoding For example you might use a square root scale when computing the radius of a circle so that the area is proportional to the associated data value var x d3 scale log domain 12 24 range 0 720 x 16 298 82699948076737 A log scale applies a logarithmic transform Be careful that your log scale s domain never crosses zero which is at infinity Domains Ranges Typically domains are derived from data while ranges are constant var x d3 scale linear domain 0 d3 max numbers range 0 720 Use d3 min and d3 max to compute the domain var x d3 scale log domain d3 extent numbers range 0 720 Use d3 extent to compute the min and max simultaneously function value d return d value var x d3 scale log domain d3 extent objects value range 0 720 Use an accessor function to derive a numeric value for objects If you prefer you can use array map instead of an accessor function Interpolators Quantitative scales support multiple interpolators D3 has a powerful set of interpolators that are used by scales and transitions It s good to understand how interpolators work Occasionally you might also find a reason to use an interpolator directly or to write your own custom interpolator var x d3 scale linear domain 12 24 range steelblue brown x 16 666586 Colors are detected automatically for RGB interpolation D3 understands CSS2 colors such as FFF and rgb 255 0 0 D3 might support perceptual color spaces in the future namely CIE L a b var x d3 scale linear domain 12 24 range 0px 720px x 16 240px String interpolation matches embedded numbers quite flexible Generic string interpolation can be used for CSS positions and sizes which unlike CSS require units such as px or em for SVG path data and other applications var x d3 scale linear domain 12 24 range steelblue brown interpolate d3 interpolateHsl x 16 3cb05f Interpolators can be set explicitly if desired Use HSL interpolation judiciously rainbow color scales hue interpolation are a generally accepted bad practice You can even interpolate objects Mousemove to see this demo This slide is contrived but object interpolation is often used for transitions of complex data objects such as donut charts or sunburst layouts Diverging Scales Sometimes you want a compound polylinear scale var x d3 scale linear domain 10 0 100 range red white green x 5 ff8080 x 50 80c080 The domain and range can have more than two values Ordinal Scales Map a discrete domain to a discrete range var x d3 scale ordinal domain A B C D range 0 10 20 30 x B 10 An ordinal scale is essentially an explicit mapping You wouldn t normally use an ordinal scale this way but I m including it as the most direct example of what an ordinal scale does The first element in the domain is mapped to the first element in the range and so on var x d3 scale category20 domain A B C D x B aec7e8 Ordinal scales are often used to assign categorical colors var x d3 scale category20 domain A B C D x E 2ca02c x E 2ca02c x domain A B C D E Unknown values are implicitly added to the domain You often don t need to assign a domain explicitly with a categorical color scale you can just start passing data to the scale and it will do the right thing However if you want a deterministic mapping for example the same colors across datasets or pages then you ll want to define the domain explicitly otherwise it is order dependent A handful of color scales are built in see also ColorBrewer var x d3 scale ordinal domain A B C D rangePoints 0 720 x B 240 Ordinal ranges can be derived from continuous ranges The rangePoints method might be used with an ordinal scatterplot var x d3 scale ordinal domain A B C D rangeRoundBands 0 720 2 x B 206 bar position x rangeBand 137 bar width Ordinal ranges are particularly useful for bar charts Here the scale returns the position of the left side of the bar while the rangeBand method returns the bar width The second argument to rangeBands here 2 is the amount of padding to reserve between bars The rangeRoundBands method is the same as rangeBands except it rounds to whole pixels to avoid blurry anti aliasing Axes D3 provides convenient labeling for scales In earlier releases you had to label the axes yourself The d3 svg axis component makes things much easier var yAxis d3 svg axis scale y orient left Create an axis for a given scale and configure as desired There are a variety of other properties you might want to configure on an axis such as the number of ticks or the tick format svg append g attr class y axis call yAxis Render the axis by calling a g selection You can also call the axis on a transition to animate changes to the domain axis path axis line fill none stroke 000 shape rendering crispEdges Customize axis appearance via CSS The CSS snippet here is a good default appearance for axes but you can customize it however you like The next slide shows a ggplot2 inspired appearance Ticks Quantitative scales can be queried for human readable values var x d3 scale linear domain 12 24 range 0 720 x ticks 5 12 14 16 18 20 22 24 The requested count is only a hint for better or worse Tick Formats See d3 format and d3 time format Marks Marks as in graphical marks or shapes the various ways in which you can represent a data point visually SVG Coordinates Absolute positioning the origin 0 0 is the top left corner Because the origin is in the top left rather than bottom left you often see y scales with an inverted range e g height 0 Use transforms to define a new origin The transform attribute on g elements lets you define a new coordinate system A translate lets you shift the origin based on margins this approach is convenient because you isolate the margin definition to a single place in your code var svg d3 select body append svg attr width outerWidth attr height outerHeight var g svg append g attr transform translate marginLeft marginTop Use margins for decorative elements such as axes SVG Basic Shapes SVG Spec rect x 0 y 0 width 0 height 0 rx 0 ry 0 Rect Note that position and size must be defined as attributes in SVG rather than styles Colors and opacity should be specified

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

  • Email Protection | CloudFlare
    is protected by CloudFlare Email addresses on that page have been hidden in order to keep them from being accessed by malicious bots You must enable Javascript in your browser in order to decode the e mail address If you have a website and are interested in protecting it in a similar way you can sign up for CloudFlare How do spammers get email addresses How does CloudFlare protect email

    Original URL path: https://bost.ocks.org/cdn-cgi/l/email-protection (2016-04-30)
    Open archived version from archive


  • The intersecting arcs can be seen in blue and red if you zoom in Third rings are rotated and cut so that each arc can represented be uniquely The red arc is the segment after the cut and the blue arc is the segment before rotated rings are in pink Lastly the arcs are deduped so that each unique arc is only represented once The first time an arc is

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



  • (No additional info available in detailed archive for this subpage)
    Original URL path: /mike/bubble-map/base.html (2016-04-30)




  • (No additional info available in detailed archive for this subpage)
    Original URL path: /mike/bubble-map/basic.html (2016-04-30)




  • (No additional info available in detailed archive for this subpage)
    Original URL path: /mike/bubble-map/sorted.html (2016-04-30)


  • Let’s Make a Bar Chart, II
    attr height barHeight data length var bar chart selectAll g data data enter append g attr transform function d i return translate 0 i barHeight bar append rect attr width x attr height barHeight 1 bar append text attr x function d return x d 3 attr y barHeight 2 attr dy 35em text function d return d script We set the svg element s size in JavaScript so that we can compute the height based on the size of the dataset data length This way the size is based on the height of each bar rather than the overall height of the chart and we ensure adequate room for labels Each bar consists of a g element which in turn contains a rect and a text We use a data join an enter selection to create a g element for each data point We then translate the g element vertically creating a local origin for positioning the bar and its associated label Since there is exactly one rect and one text element per g element we can append these elements directly to the g without needing additional data joins Data joins are only needed when creating a variable number of children based on data here we are appending just one child per parent The appended rect s and text s inherit data from their parent g element and thus we can use data to compute the bar width and label position Loading Data Let s make this chart more realistic by extracting the dataset into a separate file An external data file separates the chart implementation from its data making it easier to reuse the implementation on multiple datasets or even live data that changes over time Tab separated values TSV is a convenient tabular data format This format can be exported from Microsoft Excel and other spreadsheet programs or authored by hand in a text editor Each line represents a table row where each row consists of multiple columns separated by tabs The first line is the header row and specifies the column names Whereas before our dataset was a simple array of numbers now we ll add a descriptive name column Our data file now looks like this When authoring by hand note that delimiters tabs for TSV and commas for CSV newlines and double quotes must be escaped with double quotes name value Locke 4 Reyes 8 Ford 15 Jarrah 16 Shephard 23 Kwon 42 To use this data in a web browser we need to download the file from a web server and then parse it which converts the text of the file into usable JavaScript objects Fortunately these two tasks can be performed by a single function d3 tsv Loading data introduces a new complexity downloads are asynchronous When you call d3 tsv it returns immediately while the file downloads in the background At some point in the future when the download finishes your callback function is invoked with the new data or an

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



  •