简体   繁体   中英

How to make a bar chart for time duration with d3?

The question is quite simple but I don't really know how to do it nor how to format my data.

I just want to make a simple bar chart like this example : http://bl.ocks.org/mbostock/3885304

But instead of having A, B, C, etc on X Axis it'll be days (16/01/2017, 17/01/2017, etc.) and on Z Axis I want a time duration. Max will be 24 hours. I actually have json formatted data for each days with seconds as value.

[
  {
    "date": "2017-01-08",
    "uptime": 40320,
  },
  {
    "date": "2017-01-09",
    "uptime": 74460,
  },
  {
    "date": "2017-01-10",
    "uptime": 73500,
  },
  {
    "date": "2017-01-11",
    "uptime": 83640,
  },
  {
    "date": "2017-01-12",
    "uptime": 68520,
  }
]

Any hint ?

Your data is formatted fine. Just swap out the variable names in the linked example; date for letter and uptime for frequency . Finally since your data is already in JSON, you can inline into the <script> tag:

 <!DOCTYPE html> <meta charset="utf-8"> <style> .bar { fill: steelblue; } .bar:hover { fill: brown; } .axis--x path { display: none; } </style> <svg width="960" height="500"></svg> <script src="https://d3js.org/d3.v4.min.js"></script> <script> var svg = d3.select("svg"), margin = { top: 20, right: 20, bottom: 30, left: 40 }, width = +svg.attr("width") - margin.left - margin.right, height = +svg.attr("height") - margin.top - margin.bottom; var x = d3.scaleBand().rangeRound([0, width]).padding(0.1), y = d3.scaleLinear().rangeRound([height, 0]); var g = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var data = [{ "date": "2017-01-08", "uptime": 40320, }, { "date": "2017-01-09", "uptime": 74460, }, { "date": "2017-01-10", "uptime": 73500, }, { "date": "2017-01-11", "uptime": 83640, }, { "date": "2017-01-12", "uptime": 68520, }] data.forEach(function(d){ d.uptime = d.uptime / 3600; }); x.domain(data.map(function(d) { return d.date; })); y.domain([0, d3.max(data, function(d) { return d.uptime; })]); g.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); g.append("g") .attr("class", "axis axis--y") .call(d3.axisLeft(y)) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "0.71em") .attr("text-anchor", "end") .text("Frequency"); g.selectAll(".bar") .data(data) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d.date); }) .attr("y", function(d) { return y(d.uptime); }) .attr("width", x.bandwidth()) .attr("height", function(d) { return height - y(d.uptime); }); </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM