【问题标题】:TypeError: svg.append(...).attrs is not a function when creating charts using D3.jsTypeError: svg.append(...).attrs 不是使用 D3.js 创建图表时的函数
【发布时间】:2019-10-30 00:21:15
【问题描述】:

我正在尝试使用 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.

如何更正上面的代码?

【问题讨论】:

    标签: javascript d3.js svg bar-chart


    【解决方案1】:

    d3.attrs 不包含在默认的 D3 包中:

    您需要安装d3-selection-multi 以包含.attrs 方法。

    为了简洁起见,该模块不包含在默认的 D3 包中:建议大多数用户使用诸​​如 selection.attr 之类的单值方法,因为这些便捷方法提供的较短语法几乎没有什么好处。

    您可以将代码重写为:

    let title = svg.append('text')
      .attr('class', 'title')
      .attr('y', 24)
      .html('18 years of Interbrand’s Top Global Brands');
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 2016-06-19
    相关资源
    最近更新 更多