- D3.js 4.x Data Visualization(Third Edition)
- ?ndrew Rininsland Swizec Teller
- 381字
- 2021-07-02 23:20:27
Drawing with SVG
To draw with D3, you can add shapes manually by defining the appropriate SVG elements, or you can use helper functions that help you create advanced shapes easily.
Most of what we'll be doing in the rest of this book uses SVG. Pay attention, because this is all going to become very familiar, very quickly.
There's a bunch of stuff that is common to most D3 charts, and we're going to start off by saving ourselves a boatload of time by creating a new factory function that sets everything up for us all. Create a new folder called common/ inside lib/ and create a new file called index.js in that folder. Add the following to the file to import D3:
import * as d3 from 'd3';
We will set up a prototype that we can override later if we need to:
const protoChart = {
width: window.innerWidth,
height: window.innerHeight,
margin: {
left: 10,
right: 10,
top: 10,
bottom: 10,
},
};
This is just a plain old object with a bunch of values we'll use later on--consistent 10 pixel margin on each side, with width and height set to the interior dimensions of the browser window.
Next, we will create a factory that returns a basic chart, using the values used in the preceding code and allowing them to be overridden, as necessary:
export default function chartFactory(opts, proto = protoChart) {
const chart = Object.assign({}, proto, opts);
chart.svg = d3.select('body')
.append('svg')
.attr('id', chart.id || 'chart')
.attr('width', chart.width - chart.margin.right)
.attr('height', chart.height - chart.margin.bottom);
chart.container = chart.svg.append('g')
.attr('id', 'container')
.attr('transform', `translate(${chart.margin.left}, ${chart.margin.top})`);
return chart;
}
Here, we assign our protoChart object from before as the default value of the proto function argument. In this way, we can either override inpidual properties in the first argument or supply a whole new prototype, if we need to do something really funky. We then use d3-selection to add an SVG element to the page body, use our width, height, and margin values to size that appropriately and get bottom/right margins, and then add a group element g that we shift right and down in order to get our top/left margins.
It's simple, but it will do a lot of heavy lifting for us over the next few chapters.
- 老“碼”識途
- 零基礎學Java程序設計
- INSTANT Mercurial SCM Essentials How-to
- 人人都是網站分析師:從分析師的視角理解網站和解讀數據
- Linux:Embedded Development
- Creating Stunning Dashboards with QlikView
- Python深度學習:模型、方法與實現
- 詳解MATLAB圖形繪制技術
- Spring MVC+MyBatis開發從入門到項目實踐(超值版)
- 響應式Web設計:HTML5和CSS3實戰(第2版)
- Mastering Elasticsearch(Second Edition)
- Scratch從入門到精通
- 高效使用Greenplum:入門、進階與數據中臺
- 虛擬現實建模與編程(SketchUp+OSG開發技術)
- PostgreSQL 12 High Availability Cookbook