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
Solution 1:
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><metacharset="utf-8"><style>.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
.axis--x path {
display: none;
}
</style><svgwidth="960"height="500"></svg><scriptsrc="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) {
returnx(d.date);
})
.attr("y", function(d) {
returny(d.uptime);
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height - y(d.uptime);
});
</script>
Post a Comment for "How To Make A Bar Chart For Time Duration With D3?"