javascript - 如何获取 d3.js 图表的 JSON key

标签 javascript html d3.js

这是我的问题:我有一个包含 JSON 对象的数组,我想获取 JSON 对象的键来用它构建条形图。

这是我的数组:

var dataset = [{
      "T1": 4.23
    },
    {
      "T2": 45.62
    },
    {
      "T3": 24.78
    },
    {
      "T4": 11.41
    },
    {
      "T5": 5.19
    },
    {
      "T6": 5.15
    },
    {
      "T7": 1.99
    },
    {
      "T8": 0.93
    },
    {
      "T9": 0.61
    }
  ];

这是我绘制图表的代码:

  let width = 500;
  let heigth = 200;
  let barPadding = 1;

  let svg = d3.select("#containerChart")
    .append("svg")
    .attr("width", width)
    .attr("height", heigth);


  svg.selectAll("rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr("x", function (d, i) {
      return i + (20 + barPadding);
    })
    .attr("y", function (d) {
      return heigth - (**values of JSON object** * 2)
    })
    .att("width", 20)
    .attr("heigth", function (d) {
      return (**values of JSON object** * 2)
    })
    .attr("fill", "teal")

你知道我该怎么做吗?

预先感谢您的帮助!!

最佳答案

这是codepen这是在本地测试的代码:

<!DOCTYPE html>
<meta charset="utf-8">

<head>
    <style>

  .bar{
    fill: steelblue;
  }

  .bar:hover{
    fill: brown;
  }

    .axis {
      font: 10px sans-serif;
    }

    .axis path,
    .axis line {
      fill: none;
      stroke: #000;
      shape-rendering: crispEdges;
    }

    </style>
</head>

<body>

<script src="http://d3js.org/d3.v3.min.js"></script>

<script>
// set the dimensions of the canvas
var margin = {top: 20, right: 20, bottom: 70, left: 40},
    width = 600 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;


// set the ranges
var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);

var y = d3.scale.linear().range([height, 0]);

// define the axis
var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")


var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(10);


// add the SVG element
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", 
          "translate(" + margin.left + "," + margin.top + ")");


// load the data
d3.json("data.json", function(error, data) {


  // scale the range of the data
  x.domain(data.map(function(d) { return Object.keys(d); }));
  y.domain([0, d3.max(data, function(d) { return +d[Object.keys(d)]; })]);

  // add axis
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .selectAll("text")
      .style("text-anchor", "end")
      .attr("dx", "-.8em")
      .attr("dy", "-.55em")
      .attr("transform", "rotate(-90)" );

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 5)
      .attr("dy", ".71em")
      .style("text-anchor", "end");

  // Add bar chart
  svg.selectAll("bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(Object.keys(d)); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(+d[Object.keys(d)]); })
      .attr("height", function(d) { return height - y(+d[Object.keys(d)]); });

});

</script>

</body>

我使用 Object.keys() 将 y 轴的所有引用替换为 json 键,并获取这些键的值以放入 x 轴。您还可以使用 for...in 循环来执行相同的操作。

要在本地测试它,您必须将这两个文件托管在本地服务器上,否则您将收到 CORS 错误。您可以包含已解析的内联 json 来完全避免 CORS。

关于javascript - 如何获取 d3.js 图表的 JSON key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50860683/

相关文章:

javascript - 具有 asyc 属性的脚本仍然会阻止其他脚本执行

javascript - Node.js 客户端无法看到来自 Express 服务器的数据

javascript - 使用 mongoose 中现有集合的一部分

jquery - 滚动到一个 div

html - 如何在 Dreamweaver 中针对移动设备进行设计,同时在我拥有桌面代码的同一 CSS 中进行编码?

javascript - SimpleHTTPServer 代码 404,消息未找到文件

javascript - 带有内部链接的 DOM 菜单 - 语法问题?

android - html5 Canvas 作为应用程序

javascript - 可排序条形图不工作

javascript - d3.js 中的嵌套数组