{"id":13481620,"url":"https://github.com/gka/d3-jetpack","last_synced_at":"2025-05-16T05:04:12.971Z","repository":{"id":27252178,"uuid":"30724539","full_name":"gka/d3-jetpack","owner":"gka","description":" 🚀 Nifty convenience wrappers that speed up your daily work with d3.js","archived":false,"fork":false,"pushed_at":"2023-02-23T11:47:44.000Z","size":582,"stargazers_count":614,"open_issues_count":13,"forks_count":52,"subscribers_count":20,"default_branch":"main","last_synced_at":"2025-05-16T05:03:52.020Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gka.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-02-12T21:22:19.000Z","updated_at":"2025-04-27T04:04:28.000Z","dependencies_parsed_at":"2024-05-04T05:32:23.070Z","dependency_job_id":"b4fbfee8-add2-41f2-936b-3e17bd4cdbd2","html_url":"https://github.com/gka/d3-jetpack","commit_stats":{"total_commits":144,"total_committers":11,"mean_commits":"13.090909090909092","dds":0.5902777777777778,"last_synced_commit":"edd1456d15921f06e4b6bec1c2d4f0ed9d6e7cd0"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gka%2Fd3-jetpack","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gka%2Fd3-jetpack/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gka%2Fd3-jetpack/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gka%2Fd3-jetpack/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gka","download_url":"https://codeload.github.com/gka/d3-jetpack/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254471061,"owners_count":22076585,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T17:00:53.419Z","updated_at":"2025-05-16T05:04:12.944Z","avatar_url":"https://github.com/gka.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","Utils"],"sub_categories":[],"readme":"d3-jetpack is a set of nifty convenience wrappers that speed up your daily work with d3.js\n\n[![jetpack](http://68.media.tumblr.com/tumblr_m4kkxd8nWB1rwkrdbo1_500.jpg)](http://myjetpack.tumblr.com/post/23725103159)\n\n(comic by [Tom Gauld](http://myjetpack.tumblr.com/]))\n\n## Usage\n\nIf you use NPM, `npm install d3-jetpack`. Otherwise, download the latest [d3v4+jetpack.js](https://raw.githubusercontent.com/gka/d3-jetpack/master/build/d3v4%2Bjetpack.js).\n\nHere's what's in the package:\n\n\u003ca name=\"append\" href=\"#append\"\u003e#\u003c/a\u003e selection.\u003cb\u003eappend\u003c/b\u003e(\u003ci\u003eselector\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/append.js \"Source\")\n\nModifies `append` so it adds classes and ids.\n\n```js\nselection.append(\"div.my-class\");\nselection.append(\"div.first-class.second-class\");\nselection.append(\"div#someId\");\nselection.append(\"div#someId.some-class\");\n```\n\n\u003ca name=\"insert\" href=\"#insert\"\u003e#\u003c/a\u003e selection.\u003cb\u003einsert\u003c/b\u003e(\u003ci\u003eselector\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/insert.js \"Source\")\n\nWorks with insert, too:\n\n```js\nselection.insert(\"div.my-class\");\n```\n\n\n\u003ca name=\"appendMany\" href=\"#appendMany\"\u003e#\u003c/a\u003e selection.\u003cb\u003eappendMany\u003c/b\u003e(\u003ci\u003eselector\u003c/i\u003e, \u003ci\u003earray\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/appendMany.js \"Source\")\n\nInstead of making an empty selection, binding data to it, taking the enter selection and appending elements as separate steps:\n\n```js\nselection.selectAll('div.my-class')\n  .data(myArray)\n  .enter()\n  .append('div.my-class');\n```\n\nuse `appendMany`:\n\n```js\nselection.appendMany('div.my-class', myArray);\n```\n\n\u003ca name=\"at\" href=\"#at\"\u003e#\u003c/a\u003e selection.\u003cb\u003eat\u003c/b\u003e(\u003ci\u003ename[, value]\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/at.js \"Source\")\n\nWorks like d3v3's `.attr`. Passing an object to name sets multiple attributes, passing a string returns a single attribute and passing a string \u0026 second argument sets a single attribute.\n\nTo avoid having to use quotes around attributes and styles with hyphens when using the object notation, camelCase keys are hyphenated. Instead of:\n\n```js\nselection\n    .attr('stroke-width', 10)\n    .attr('text-anchor', 'end')\n    .attr('font-weight', 600)\n```\n\nor with [d3-selection-multi](https://github.com/d3/d3-selection-multi):\n\n```js\nselection.attrs({'stroke-width': 10, 'text-anchor': 'end', 'font-weight': 600})\n```\n\nyou can write:\n\n```js\nselection.at({fontSize: 10, textAnchor: 'end', fontWeight: 600})\n```\n\nWith syntax highlighting on, it is a little easier to see the difference between keys and values when everything isn't a string. Plus there's less typing!\n\n\u003ca name=\"st\" href=\"#st\"\u003e#\u003c/a\u003e selection.\u003cb\u003est\u003c/b\u003e(\u003ci\u003ename[, value]\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/st.js \"Source\")\n\nLike `at`, but for `style`. Additionally, when a number is passed to a style that requires a unit of measure, like `margin-top` or `font-size`, `px` is automatically appended. Instead of\n\n```js\nselection\n    .style('margin-top', height/2 + 'px')\n    .style('font-size', '40px')\n    .style('width', width - 80 + 'px')\n```\n\nThe `+ px`s can also be dropped:\n\n```js\nselection.st({marginTop: height/2, fontSize: 40, width: width - 80})\n```\n\n\u003ca name=\"selectAppend\" href=\"#selectAppend\"\u003e#\u003c/a\u003e d3.\u003cb\u003eselectAppend\u003c/b\u003e(\u003ci\u003eselector\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/selectAppend.js \"Source\")\n\nSelects the first element that matches the specified selector string or if no elements match the selector, it will append an element. This is often handy for elements which are required as part of the DOM hierachy, especially when making repeated calls to the same code. When appending it will also add id and classes, same as Jetpack's [append](#append)\n\n```js\nd3.selectAppend('ul.fruits')\n    .selectAll('li')\n    .data(data)\n```\n\n\u003ca name=\"parent\" href=\"#parent\"\u003e#\u003c/a\u003e d3.\u003cb\u003eparent\u003c/b\u003e(\u003ci\u003e\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/parent.js \"Source\")\n\nReturns the parent of each element in the selection:\n\n```js\nd3.selectAll('span')\n    .style('color', 'red')\n  .parent()\n    .style('background', 'yellow')\n```\n\nThis might mess with the joined data and/or return duplicate elements. Usually better to save a variable, but sometimes useful when working with nested html.\n\n\u003ca name=\"translate\" href=\"#translate\"\u003e#\u003c/a\u003e selection.\u003cb\u003etranslate\u003c/b\u003e(\u003ci\u003exyPosition\u003c/i\u003e, [\u003ci\u003edim\u003c/i\u003e]) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/translate.js \"Source\")\n\nHow I hated writing ``.attr('transform', function(d) { return 'translate()'; })`` a thousand times...\n\n```js\nsvg.append('g').translate([margin.left, margin.top]);\ncircle.translate(function(d) { return [x(d.date), y(d.value)]; });\n```\n\nIf you only want to set a *single* dimension you can tell translate by passing 0 (for x) or 1 (for y) as second argument:\n\n```js\nx_ticks.translate(d3.f(x), 0);\ny_ticks.translate(d3.f(y), 1);\n```\n\nHTML is supported as well! `translate` uses style transforms with px units if the first element in the selection is HTML.\n\n```js\nsvg_selection.translate([40,20]); // will set attribute transform=\"translate(40, 20)\"\nhtml_selection.translate([40,20]); // will set style.transform = \"translate(40px, 20px)\"\n```\n\n\u003ca name=\"tspans\" href=\"#tspans\"\u003e#\u003c/a\u003e selection.\u003cb\u003etspans\u003c/b\u003e(\u003ci\u003earray\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/tspans.js \"Source\")\n\nFor multi-line SVG text\n\n```js\nselection.append('text')\n    .tspans(function(d) {\n        return d.text.split('\\n');\n    });\nselection.append('text').tspans(['Multiple', 'lines'], 20);\n```\n\nThe optional second argument sets the line height (defaults to 15).\n\n\u003ca name=\"wordwrap\" href=\"#wordwrap\"\u003e#\u003c/a\u003e d3.\u003cb\u003ewordwrap\u003c/b\u003e(\u003ci\u003etext\u003c/i\u003e, [\u003ci\u003elineWidth\u003c/i\u003e]) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/wordwrap.js \"Source\")\n\nComes in handy with the tspans:\n\n```js\nselection.append('text')\n    .tspans(function(d) {\n        return d3.wordwrap(text, 15);  // break line after 15 characters\n    });\n```\n\n\u003ca name=\"f\" href=\"#f\"\u003e#\u003c/a\u003e d3.\u003cb\u003ef\u003c/b\u003e(\u003ci\u003ekey\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/f.js \"Source\")\n\n``d3.f`` takes a string|number and returns a function that takes an object and returns whatever property the string is named. This clears away much of verbose function(d){ return ... } syntax in ECMAScript 5:\n\n```js\nx.domain(d3.extent(items, function(d){ return d.price; }));\n```\n\nbecomes\n\n```js\nx.domain(d3.extent(items, d3.f('price'));\n```\n\nd3.f even accepts multiple accessors and will execute them in the order of appearance. So for instance, let's say we have an array of polygon objects like this ``{ points: [{x: 0, y: 3}, ...] }`` we can get the first ``y`` coordinates using:\n\n```js\nvar firstY = polygons.map(d3.f('points', 0, 'y'));\n```\n\nSince we use this little function quite a lot, we usually set `var ƒ = d3.f` (type with [alt] + f on Macs). Also, [in @1wheel's blog](http://roadtolarissa.com/blog/2014/06/23/even-fewer-lamdas-with-d3/) you can read more about the rationale behind ƒ.\n\n\u003ca name=\"ascendingKey\" href=\"#ascendingKey\"\u003e#\u003c/a\u003e d3.\u003cb\u003eascendingKey\u003c/b\u003e(\u003ci\u003ekey\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/ascendingKey.js \"Source\")\n\n\u003ca name=\"descendingKey\" href=\"#descendingKey\"\u003e#\u003c/a\u003e d3.\u003cb\u003edescendingKey\u003c/b\u003e(\u003ci\u003ekey\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/descendingKey.js \"Source\")\n\nThese functions operate like d3.ascending / d3.descending but you can pass a key string or key function which will be used to specify the property by which to sort an array of objects.\n\n```js\nvar fruits = [{ name: \"Apple\", color: \"green\" }, { name: \"Banana\", color: \"yellow\" }];\nfruits.sort(d3.ascendingKey('color'));\n```\n\n\u003ca name=\"timer\" href=\"#timer\"\u003e#\u003c/a\u003e d3.\u003cb\u003etimer\u003c/b\u003e(\u003ci\u003ecallback[, delay[, time[, namespace]]]\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/timer.js \"Source\")\n\n`d3.timer`, `d3.timeout` and `d3.interval` all now take an optional namespace argument. Previous timers with the same namespace as a new timer are stopped.\n\n\u003ca name=\"nestBy\" href=\"#nestBy\"\u003e#\u003c/a\u003e d3.\u003cb\u003enestBy\u003c/b\u003e(\u003ci\u003earray, key\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/nestBy.js \"Source\")\n\nShorthand for `d3.nest().key(key).entries(array)`. Returns an array of arrays, instead of a `key`/`value` pairs. The `key` property of each array is equal the value returned by the `key` function when it is called with element of the array.\n\n```js\nd3.nest()\n    .key(d =\u003e d.year)\n    .entries(yields)\n    .forEach(function(d){\n        console.log('Count in ' + d.key + ': ' + d.values.length) })\n```\n\nto\n\n```js\nd3.nestBy(yields, d =\u003e d.year).forEach(function(d){\n    console.log('Count in ' + d.key  + ': ' + d.length) })\n```\n\n\u003ca\nname=\"loadData\" href=\"#loadData\"\u003e#\u003c/a\u003e d3.\u003cb\u003eloadData\u003c/b\u003e(\u003ci\u003efile1, file2, file3, ..., callback\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/loadData.js \"Source\")\n\nTakes any number of files paths and loads them with `queue`, `d3.csv` and `d3.json`. After all the files have loaded, calls the `callback` function with the first error (or null if there are none) as the first argument and an array of the loaded files as the second. Instead of:\n\n```js\nd3.queue()\n    .defer(d3.csv, 'state-data.csv')\n    .defer(d3.tsv, 'county-data.tsv')\n    .defer(d3.json, 'us.json')\n    .awaitAll(function(err, res){\n        var states = res[0],\n            counties = res[1],\n            us = res[2]\n    })\n```\n\nif your file types match their extensions, you can use:\n\n```js\nd3.loadData('state-data.csv', 'county-data.tsv', 'us.json', function(err, res){\n    var states = res[0],\n        counties = res[1],\n        us = res[2]\n})\n```\n\n\n\u003ca name=\"round\" href=\"#round\"\u003e#\u003c/a\u003e d3.\u003cb\u003eround\u003c/b\u003e(\u003ci\u003ex\u003c/i\u003e, \u003ci\u003eprecisions\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/round.js \"Source\")\n\nA useful short-hand method for `+d3.format('.'+precision+'f')(x)` also known as `+x.toFixed(precision)`. Note that this code is [fundamentally broken](https://twitter.com/mbostock/status/776448389814718465) but still works fine 99% of the time.\n\n```js\nd3.round(1.2345, 2) // 1.23\n```\n\n\n\u003ca name=\"clamp\" href=\"#clamp\"\u003e#\u003c/a\u003e d3.\u003cb\u003eclamp\u003c/b\u003e(\u003ci\u003emin\u003c/i\u003e, \u003ci\u003eval\u003c/i\u003e, \u003ci\u003emax\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/clamp.js \"Source\")\n\nShort for `Math.max(min, Math.min(max, val))`.\n\n```js\nd3.clamp(0, -10, 200) // 0\nd3.clamp(0, 110, 200) // 110\nd3.clamp(0, 410, 200) // 200\n```\n\n\n\u003ca name=\"attachTooltip\" href=\"#attachTooltip\"\u003e#\u003c/a\u003e d3.\u003cb\u003eattachTooltip\u003c/b\u003e(\u003ci\u003eselector\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/attachTooltip.js \"Source\")\n\nAttaches a light weight tooltip that prints out all of an objects properties on click. No more `\u003e d3.select($0).datum()`!\n\n```js\nd3.select('body').selectAppend('div.tooltip')\n\ncircles.call(d3.attachTooltip)\n```\n\nFor formated tooltips, update the html of the tooltip on mouseover:\n\n```js\ncircles\n    .call(d3.attachTooltip)\n    .on('mouseover', function(d){\n      d3.select('.tooltip').html(\"Number of \" + d.key + \": \" + d.length) })\n```\n\nMake sure to add a  `\u003cdiv class='tooltip'\u003e\u003c/div\u003e` and that there's some tooltip css on the page:\n\n```css\n.tooltip {\n  top: -1000px;\n  position: fixed;\n  padding: 10px;\n  background: rgba(255, 255, 255, .90);\n  border: 1px solid lightgray;\n  pointer-events: none;\n}\n.tooltip-hidden{\n  opacity: 0;\n  transition: all .3s;\n  transition-delay: .1s;\n}\n\n@media (max-width: 590px){\n  div.tooltip{\n    bottom: -1px;\n    width: calc(100%);\n    left: -1px !important;\n    right: -1px !important;\n    top: auto !important;\n    width: auto !important;\n  }\n}\n```\n\n\u003ca name=\"conventions\" href=\"#conventions\"\u003e#\u003c/a\u003e d3.\u003cb\u003econventions\u003c/b\u003e(\u003ci\u003e[options]\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/conventions.js \"Source\")\n\n`d3.conventions([config])` creates an SVG with a G element translated to follow the [margin convention](http://bl.ocks.org/mbostock/3019563). `d3.conventions` returns an object with the dimensions and location of the created element. Passing in a config object overrides the default dimensions.\n\nTo create this html:\n\n```html\n\u003cdiv id=\"graph\"\u003e\n  \u003csvg width=900 height=500\u003e\n    \u003cg transform=\"translate(20, 20)\"\u003e\n  \u003c/svg\u003e\n\u003c/div\u003e\n```\n\nYou could run this:\n\n```js\nvar sel = d3.select('#graph')\nvar totalWidth  = 900\nvar totalHeight = 500\nvar {svg, margin, height, width} = d3.conventions({sel, totalHeight, totalWidth})\n\nsvg     // d3 selection of G representing chart area\nmargin  // padding around G, defaults to {top: 20, left: 20, height: 20, width: 20}\nheight  // height of charting area (500 - 20 - 20 = 460 here)\nweight  // width  of charting area (900 - 20 - 20 = 460 here)\n```\n\n\n`sel`: `d3.selection` of the element the SVG was appended to. Defaults to `d3.select(\"body\")`, but can be specified by passing in an object: `d3.conventions({sel: d3.select(\"#graph-container\")})` appends an SVG to `#graph-container`.\n\n`totalWidth`/`totalHeight`: size of the SVG. By default uses the offsetWidth and offsetHeight of `sel`. `d3.conventions({totalHeight: 500})` makes a responsive chart with a fixed height of 500.\n\n`margin`:  Individual keys override the defaults. `d3.conventions({margins: {top: 50}})` sets the top margin to 50 and leaves the others at 20\n\n`width`/`height`: inner charting area. If passed into conventions, `totalWidth` and `totalHeight` are set to the extent of the charting area plus the margins. `d3.conventions({width: 200, height: 200, margin: {top: 50}})` creates a square charting area with extra top margin.\n\n`layers`:  `d3.conventions` can also create multiple canvas and div elements. `d3.conventions({layers: 'sdc'})` makes an **S**VG, **D**IV and canvas **c**tx with the same margin and size. Layers are positioned absolutely on top of each other in the order listed in the layer string. To create an SVG with two canvas elements on top:\n\n```js\nvar {layers: [svg, bg_ctx, fg_ctx]} = d3.conventions({layers: 'scc'})\n```\n\n`layers` defaults to `'s'`, creating a single SVG.\n\nMost charts use two linear scales and axii. `d3.conventions` returns some functions to get you started, but feel free to use something else!\n\n`x`: `scaleLinear().range([0, width])`. To use a different scale: `d3.conventions({x: d3.scaleSqrt()})`.\n\n`y`: `scaleLinear().range([height, 0])`.\n\n`xAxis`: `axisBottom().scale(x)`.\n\n`yAxis`: `axisLeft().scale(y)`.\n\n\u003ca name=\"drawAxis\" href=\"#drawAxis\"\u003e#\u003c/a\u003e d3.\u003cb\u003edrawAxis\u003c/b\u003e(\u003ci\u003e{svg, xAxis, yAxis, height}\u003c/i\u003e) [\u003c\u003e](https://github.com/gka/d3-jetpack/blob/master/src/drawAxis.js \"Source\")\n\nAppends an `xAxis` aligned to the bottom of `svg` and a `yAxis` aligned to the left. You can pass the output of `conventions` directly to `drawAxis`, but make sure to set an `x` and `y` domain first!\n\n```\nvar c = d3.conventions()\nc.x.domain([1990, 2015])\nc.y.domain(d3.extent(data, d =\u003e d.cost))\nd3.drawAxis(c)\n```\n\n## Essential jetpack\n\nIf you think jetpack adds too much to your build, try starting with the essential jetpack and adding features as you need them.\n\n```js\n// essentials (insert, append, appendMany etc)\nimport {f} from 'd3-jetpack/essentials';\n// get some extra stuff\nimport attachTooltip from 'd3-jetpack/src/attachTooltip'\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgka%2Fd3-jetpack","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgka%2Fd3-jetpack","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgka%2Fd3-jetpack/lists"}