[D3] Margin Convention with D3 v4

You can’t add axes to a chart if you don’t make room for them. To that end, the D3 community has adopted a simple convention for defining margin sizes that shields most of your code from having to know or care about them. This lesson demonstrates the margin convention and the simple flexibility it adds to your D3 projects.

 

var margin = { top: 10, right: 20, bottom: 25, left: 25 };
var width = 425 - margin.left - margin.right;
var height = 625 - margin.top - margin.bottom;

var svg = d3.select('.chart')
  .append('svg')
    .attr('width', width + margin.left + margin.right)
    .attr('height', height + margin.top + margin.bottom)
  .append('g')
    .attr('transform', `translate(${margin.left}, ${margin.top})`);

svg.append('rect')
  .attr('width', width / 2)
  .attr('height', height)
  .style('fill', 'lightblue')
  .style('stroke', 'green');

svg.append('rect')
  .attr('x', width / 2)
  .attr('width', width / 2)
  .attr('height', height)
  .style('fill', 'lightblue')
  .style('stroke', 'green');

 

 

posted @ 2017-08-07 18:23  Zhentiw  阅读(316)  评论(0编辑  收藏  举报