2.0.0 • Published 10 years ago
d3-convention v2.0.0
d3-convention
D3 Margin Convention encoded as an npm package. Idea "forked" from 1wheel/d3-starterkit
Installation
d3-convention depends on d3 as a peer dependency
npm install d3 d3-conventionExample
var c = require('d3-convention')()
c.svg.append('rect')
.attr({
width: c.x(0.5), // 50% wide
height: c.y(0.5), // 50% high
x: c.x(0.25), // Center horizontally
y: c.y(0.75) // Center vertically
})
.style('fill', 'steelblue')Reference
All options have sane defaults, however d3Convention([opts]) accepts:
var c = d3Convention({
margin: Number || {top: Number, right: Number, bottom: Number, left: Number},
width: Number,
height: Number,
parent: DOMElement || String || d3.select,
svg: SVGElement || String || d3.select // preferably SVGSVGElement
})It will mutate the originally passed opts Object, with these properties:
c.marginis an Object with the properties{top, right, bottom, left}either the originally passedopts.marginobject, an object expanded from the Number passed or the default{top: 20, right: 10, bottom: 20, left: 10}c.widthis the "scene" width excluding margin on the left and right side. Defaults to960 - margin.left - margin.right = 940c.height, under the same constraints asc.width. Defaults to460c.outerWidththe width of the SVG element. Calculated fromc.width + c.margin.left + c.margin.right. Default resolves to960c.outerHeightthe actual height of the "drawing scene". Calculated fromc.height + c.margin.top + c.margin.bottom. Default resolves to500c.parentis either the passedopts.parentor a D3 selection with thebodyelement. This is where thec.svgelement is inserted, unlessopts.svgis passed, in which case this property is ignoredc.svgis a newly inserted<g>element which istranslated. We will try to set thewidthandheightattrs of this, as well as appending a<g>element which is translated. However specifyingopts.svgallows you to some of your SVG markup and just insert the conventions in a child node, eg. if you hardcode something like a legendc.xis ad3.scale.linearscale that maps[0, 1] -> [0, opts.innerWidht]c.yis a flippedd3.scale.linearscale so that0is at the bottom of the scene. It maps[0, 1] -> [opts.innerHeight, 0](note the upside-downness)
{
margin: {top: Number, right: Number, bottom: Number, left: Number},
width: opts.width || 960,
height: opts.height || 500,
innerWidth: Number,
innerHeight: Number,
parent: d3.select(opts.parent || HTMLBodyElement),
svg: s3.select(SVGGElement),
x: d3.scale.linear,
y: d3.scale.linear
}Notable Differences
d3-convention was inspired by Block #3019563
and 1wheel/d3-starterkit.
It differs from d3-starterkit in several ways:
marginis subtracted, whered3-starterkitaddsmarginto your specifiedwidthandheight- This does not return the same breadth of scales by default
- This does not return any axis
parentSelisparent. This lets you pass whateverd3.selectaccepts, it beingElement, selector or an existingd3.selection