Skip to content

Instantly share code, notes, and snippets.

@caravinden
Last active May 10, 2018 14:11
Show Gist options
  • Save caravinden/d04238c4c9770020ff6867ee92c7dac1 to your computer and use it in GitHub Desktop.
Save caravinden/d04238c4c9770020ff6867ee92c7dac1 to your computer and use it in GitHub Desktop.
Bar chart implementation using d3.v5
<!DOCTYPE html>
<svg width="960" height="500"></svg>
<style>
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
</style>
// <script src="https://d3js.org/d3.v5.min.js"></script>
<script src="//d3js.org/d3.v5.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {
top: 20,
right: 20,
bottom: 30,
left: 50
},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var parseTime = d3.timeParse("%d-%b-%y");
var x = d3.scaleBand()
.rangeRound([0, width])
.padding(0.1);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
d3.tsv("morley.tsv").then(function (data) {
x.domain(data.map(function (d) {
return d.Run;
}));
y.domain([0, d3.max(data, function (d) {
return Number(d.Speed);
})]);
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
g.append("g")
.call(d3.axisLeft(y))
.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Speed");
g.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function (d) {
return x(d.Run);
})
.attr("y", function (d) {
return y(Number(d.Speed));
})
.attr("width", x.bandwidth())
.attr("height", function (d) {
return height - y(Number(d.Speed));
});
});
</script>
Expt Run Speed
1 1 850
1 2 740
1 3 900
1 4 1070
1 5 930
1 6 850
1 7 950
1 8 980
1 9 980
1 10 880
1 11 1000
1 12 980
1 13 930
1 14 650
1 15 760
1 16 810
1 17 1000
1 18 1000
1 19 960
1 20 960
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment