Skip to content

Instantly share code, notes, and snippets.

@alanvillalobos
Last active December 13, 2022 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alanvillalobos/14e9f0d80ea6b0d8083ba95a9d571d13 to your computer and use it in GitHub Desktop.
Save alanvillalobos/14e9f0d80ea6b0d8083ba95a9d571d13 to your computer and use it in GitHub Desktop.
D3.js v4 Example/Tutorial: Responsive Bar Chart
license: cc-by-4.0

Responsive Bar Chart

A D3.js v4 Example/Tutorial

In D3.js examples a common theme that pops up is the use of a fixed size svg. I typically have to make the same set of modifications to get a resposive svg.

Here is a simple example (I hope) of said modifications. I took this original bar chart from mbostock based on D3.js v4 and split up the code to make the chart responsive when:

  • Data is loaded
  • The browser window / svg is resized

Open in a new window and resize to see it in action.

The original logic has been split up into SETUP, DRAWING, and LOADING DATA.

For example:

  • Setting the axis range is dependent on browser/svg size, so it goes in DRAWING.
  • Setting the axis domain is dependent on the data itself, so it goes in LOADING DATA.
  • SETUP contains stuff that does not change (is neither size nor data dependent).
letter frequency
A .08167
B .01492
C .02782
D .04253
E .12702
F .02288
G .02015
H .06094
I .06966
J .00153
K .00772
L .04025
M .02406
N .06749
O .07507
P .01929
Q .00095
R .05987
S .06327
T .09056
U .02758
V .00978
W .02360
X .00150
Y .01974
Z .00074
<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font-family: sans-serif;
}
.bar {
fill: cornflowerblue;
}
.bar:hover {
fill: pink;
}
.axis--x path {
display: none;
}
</style>
<svg width="100%" height="500px"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
// SETUP
var svg = d3.select("svg"),
margin = { top: 20, right: 20, bottom: 30, left: 40 },
x = d3.scaleBand().padding(0.1),
y = d3.scaleLinear(),
theData = undefined;
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
g.append("g")
.attr("class", "axis axis--x");
g.append("g")
.attr("class", "axis axis--y");
g.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Frequency");
// DRAWING
function draw() {
var bounds = svg.node().getBoundingClientRect(),
width = bounds.width - margin.left - margin.right,
height = bounds.height - margin.top - margin.bottom;
x.rangeRound([0, width]);
y.rangeRound([height, 0]);
g.select(".axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
g.select(".axis--y")
.call(d3.axisLeft(y).ticks(10, "%"));
var bars = g.selectAll(".bar")
.data(theData);
// ENTER
bars
.enter().append("rect")
.attr("class", "bar")
.attr("x", function (d) { return x(d.letter); })
.attr("y", function (d) { return y(d.frequency); })
.attr("width", x.bandwidth())
.attr("height", function (d) { return height - y(d.frequency); });
// UPDATE
bars.attr("x", function (d) { return x(d.letter); })
.attr("y", function (d) { return y(d.frequency); })
.attr("width", x.bandwidth())
.attr("height", function (d) { return height - y(d.frequency); });
// EXIT
bars.exit()
.remove();
}
// LOADING DATA
function loadData(tsvFile) {
d3.tsv(tsvFile, function (d) {
d.frequency = +d.frequency;
return d;
}, function (error, data) {
if (error) throw error;
theData = data;
x.domain(theData.map(function (d) { return d.letter; }));
y.domain([0, d3.max(theData, function (d) { return d.frequency; })]);
draw();
});
}
// START!
window.addEventListener("resize", draw);
loadData("data.tsv");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment