gpt4 book ai didi

javascript - 如何使用带序号的 d3.symbols

转载 作者:行者123 更新时间:2023-11-29 20:48:12 27 4
gpt4 key购买 nike

TL;DR:如何通过 d3.symbols 获得 scaleOrdinal?

我希望使用 d3.symbols对于序数尺度,对应于某些数据的分类属性。

d3.symbols

An array containing the set of all built-in symbol types: circle, cross, diamond, square, star, triangle, and wye. Useful for constructing the range of an ordinal scale should you wish to use a shape encoding for categorical data.

这是我认为可行的方法:

var svg = d3.select('#graph-container').append('svg').attr('xmlns', 'http://www.w3.org/2000/svg');
var g = svg.append('g');

var data = [{type: 'a'}, {type: 'a'}, {type: 'a'}, {type: 'b'}, {type: 'b'}, {type: 'c'}];

var shape = d3.scaleOrdinal(d3.symbols);

var s = g.selectAll('.symbol').data(data);

/* Does not render */
s.enter()
.append('path')
.attr('d', d => shape(d.type))
.attr('x', (d, i) => i * 20)
.attr('y', 50);

/* Sanity Check: Properly renders */
s.enter()
.append('circle')
.attr('r',7)
.attr('cx', (d, i) => (i+1)*20)
.attr('cy', 100);
<script src="https://d3js.org/d3.v5.min.js"></script>
<div id="graph-container"></div>

(或者参见 fiddle )。

不幸的是,上面的代码失败了:

Error: <path> attribute d: Expected moveto path command ('M' or 'm'), "[object Object]".

显然 shape(d.type) 没有返回有效路径。它实际上返回一个对象,该对象只有一个名为 draw 的函数,即它看起来像 { draw: function() { ... } } ,大概指的是 this draw method .不幸的是,调用该绘制方法也不会产生有效路径。

最佳答案

你错过了符号生成器本身......

var symbol = d3.symbol();

...您将向其传递类型:

s.enter()
.append('path')
.attr('d', d => symbol.type(shape(d.type))())
//etc...

此外,<path>我们没有xy属性。

下面是修改后的代码:

var svg = d3.select('#graph-container').append('svg').attr('xmlns', 'http://www.w3.org/2000/svg');
var g = svg.append('g');

var data = [{
type: 'a'
}, {
type: 'a'
}, {
type: 'a'
}, {
type: 'b'
}, {
type: 'b'
}, {
type: 'c'
}];

var shape = d3.scaleOrdinal(d3.symbols);

var symbol = d3.symbol();

var s = g.selectAll('.symbol').data(data);

/* Does not render */
s.enter()
.append('path')
.attr('d', d => symbol.type(shape(d.type))())
.attr("transform", (_, i) => "translate(" + (20 + i * 20) + ",50)")
.attr('fill', 'black');

/* Properly renders */
s.enter()
.append('circle')
.attr('r', 7)
.attr('cx', (d, i) => (i + 1) * 20)
.attr('cy', 100)
.attr('fill', 'black');
<div id="graph-container"></div>
<script src="https://d3js.org/d3.v5.min.js"></script>

关于javascript - 如何使用带序号的 d3.symbols,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53403371/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com