我正在尝试使用D3.js创建赛车条形图。我刚接触该库,因此尝试修改this example以了解该库的工作方式。
不幸的是,我收到以下错误:TypeError: svg.append(...).attrs is not a function.
这是我的代码:
<script>
tickDuration = 300;
top_n = 20;
height = 768;
width = 1366;
(function(){
const svg = d3
.select("body")
.append("svg")
.attr("width", 1366)
.attr("height", 768);
const margin = {
top: 80,
right: 0,
bottom: 5,
left: 0
};
let barPadding = (height-(margin.bottom+margin.top))/(top_n*5);
let title = svg.append('text')
.attrs({
class: 'title',
y: 24
})
.html('18 years of Interbrand’s Top Global Brands');
// More code but the above lines are causing the error.
我该如何纠正以上代码?
最佳答案
d3.attrs
不包含在默认D3捆绑包中:
您需要安装d3-selection-multi来包含.attrs
方法。
为了简化起见,默认D3捆绑包中不包含此模块:对于大多数用户,建议使用select.attr之类的单值方法,因为这些便捷方法提供的较短语法几乎没有好处。
您可以将代码重写为:
let title = svg.append('text')
.attr('class', 'title')
.attr('y', 24)
.html('18 years of Interbrand’s Top Global Brands');