javascript - 如何使用 D3.js 访问 JSON 数据?

标签 javascript json d3.js

我有一个外部 JSON 文件,结构如下:

{
 data: [
       {
        0: 'cat',
        1: 232,
        2: 45
       },
       {
        0: 'dog',
        1: 21,
        2: 9
       },
       {
        0: 'lion',
        1: 32,
        2: 5
       },
       {
        0: 'elephant',
        1: 9,
        2: 4
       },
       ]
}

使用 d3.js 我想使用键 2 访问条形图中高度的数据,因此我进行了设置:

d3.select('#chart').append('svg')
    .selectAll('rect')
    .data(data)
    .enter()
    .append('rect')
    .attr('width', barWidth)
    .attr('height', function(d) {
        return d.data['2'];
    });

我可以看到 SVG Canvas ,但无法获取条形图高度的矩形,有人有什么想法吗?

谢谢

最佳答案

我更改了一些内容,使代码能够像默认条形图一样发挥作用。您的主要问题是使用 d.data 而不是 d。之后,您必须设置 xy 坐标以及交替颜色(或使用 x 进行填充),以便矩形不会' t 彼此重叠。

var width = 30;
var padding = 5;
var chartheight = 100;
d3.select('#chart').append('svg')
  .selectAll('rect')
  .data(data)
  .enter()
  .append('rect')
  .attr('width', width)
  .attr('height', function(d) {
    return d[2];
  })
  .attr('x', function(d, i) {
    return i*(width + padding);
  })
  .attr('y', function(d, i) {
    return chartheight - d[2];
  });

d3.selectAll('rect')
  .style('fill', function(d, i) {
    return i % 2 == 0 ? "#0f0" : "#00f";
  });

关于javascript - 如何使用 D3.js 访问 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29061211/

相关文章:

c# - 返回 ajax 请求错误的最佳方式是什么?

json - 哪些工具将允许 JSON 请求编写脚本和自动化(如 SOAP UI)?

javascript - 方法链接- d3.js

javascript - Handlebars.js 在数据标签中嵌入文字 json 对象

javascript - 当我最大化窗口或返回窗口模式时,$(window).resize() 事件在 Chrome 中不起作用

jquery - 无法使用 jQuery/knockout 获取 JSON 对象的文本值

d3.js - 带有 ES6 模块的 d3 v4.0 自定义构建

javascript - 使用按钮清除表单字段

javascript - 如何在 JSDT 大纲 View 中指示公共(public)/ protected /私有(private)成员?

javascript - 强制从分配的 SVG 大小绘制有向图