d3.js——使用svg

14次阅读

共计 1767 个字符,预计需要花费 5 分钟才能阅读完成。

相比 HTML 元素,使用 SVG 可以绘制出更多的图形,此文尝试将 d3.js 与 SVG 结合 由于我也是第一次使用 SVG,所以主要根据此篇 blog 的顺序来 Let’s Make a Bar Chart, II
静态 SVG 使用
手打 SVG
<style>
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
</style>
<svg class=”chart” width=”420″ height=”120″>
<g transform=”translate(0,0)”>
<rect width=”40″ height=”19″></rect>
<text x=”37″ y=”9.5″ dy=”.35em”>4</text>
</g>
<g transform=”translate(0,20)”>
<rect width=”80″ height=”19″></rect>
<text x=”77″ y=”9.5″ dy=”.35em”>8</text>
</g>
<g transform=”translate(0,40)”>
<rect width=”150″ height=”19″></rect>
<text x=”147″ y=”9.5″ dy=”.35em”>15</text>
</g>
<g transform=”translate(0,60)”>
<rect width=”160″ height=”19″></rect>
<text x=”157″ y=”9.5″ dy=”.35em”>16</text>
</g>
<g transform=”translate(0,80)”>
<rect width=”230″ height=”19″></rect>
<text x=”227″ y=”9.5″ dy=”.35em”>23</text>
</g>
<g transform=”translate(0,100)”>
<rect width=”420″ height=”19″></rect>
<text x=”417″ y=”9.5″ dy=”.35em”>42</text>
</g>
</svg>

g 元素:用于组合对象的容器,添加到 g 元素上的变换会应用到所有子元素上 rect 与 text 就没啥好讲了 同时,在 SVG 中有一个容易混淆的点:哪些样式一定要写在属性之中(比如 rect 的 width),哪些样式可以通过 style 表现(如 fill,当然他们也可以写在属性之中,但不知道为什么优先级低于 class 给予的样式)。一个比较好记的方法就是:形状几何(如 rect 的 width)要写在属性之中,修饰类的(如 fill)可通过 style 表现
d3 生成 SVG
先贴代码,CSS 不变
let data = [4, 8, 15, 16, 23, 42];
let width = 420,
barHeight = 20;
let x = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([0, width]);
let chart = d3.select(‘.chart’)
.attr(‘width’, width)
.attr(‘height’, barHeight * data.length);
let bar = chart.selectAll(‘g’) // 数据绑定在 g 上
.data(data)
.enter().append(‘g’)
.attr(‘transform’, (d, i) => {return ‘translate(0,’ + i * barHeight + ‘)’});
bar.append(‘rect’)
.attr(‘width’, d => x(d))
.attr(‘height’, barHeight – 1);
bar.append(‘text’)
.attr(‘x’, d => x(d) – 3) // 字符 x 轴位置
.attr(‘y’, barHeight/2) // 字符 y 轴位置
.attr(‘dy’, ‘.35em’) // 字符相对位置
.text(d => d);
其实差别不是特别多,只不过是用了 SVG,并且把数据绑在 g 上,不用做另外的数据绑定
加载数据
d3.tsv() 可以用于加载解析 TSV 格式的数据
总结
本文主要是讲述了对 svg 的使用,但核心思想还是不变的
参考资料
Let’s Make a Bar Chart, II SVG 文本

正文完
 0