Skip to content

Instantly share code, notes, and snippets.

@ColinEberhardt
Last active May 28, 2019 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ColinEberhardt/8845df1f2c6b496148eb4e3b02c238ac to your computer and use it in GitHub Desktop.
Save ColinEberhardt/8845df1f2c6b496148eb4e3b02c238ac to your computer and use it in GitHub Desktop.
Let's build a bar chart - d3fc version
license: mit

A re-implementation of Mike Bostock's classic "Let's Make a Bar Chart" example, using d3fc. This example highlights the power of the decorate pattern, with the bar colour changed on decorate, and value labels added.

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>
<!-- include polyfills for custom event, Symbol and Custom Elements -->
<script src="//unpkg.com/babel-polyfill@6.26.0/dist/polyfill.js"></script>
<script src="//unpkg.com/custom-event-polyfill@0.3.0/custom-event-polyfill.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/document-register-element/1.8.0/document-register-element.js"></script>
<!-- use babel so that we can use arrow functions and other goodness in this block! -->
<script src="//unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="//unpkg.com/d3@5.5.0"></script>
<script src="//unpkg.com/d3fc@14.0.41"></script>
<style>
#chart {
width: 100%;
height: 500px;
}
.x-axis .domain {
display: none;
}
.bar-label {
text-anchor: middle;
font-size: 12px;
fill: black;
}
</style>
<div id="chart"></div>
<script type='text/babel'>
const isVowel = (letter) => 'AEIOU'.indexOf(letter) !== -1;
var barSeries = fc.autoBandwidth(fc.seriesSvgBar())
.crossValue(d => d.letter)
.align('left')
.mainValue(d => d.frequency)
.decorate((selection) => {
selection.select('path')
.style('fill', d => isVowel(d.letter) ? 'indianred' : 'steelblue');
selection.enter()
.append('text')
.attr('class', 'bar-label')
.attr('transform', 'translate(0, -5)')
.text(d => d3.format('.1%')(d.frequency));
});
d3.tsv("data.tsv", d => {
d.frequency = +d.frequency;
return d;
}).then(data => {
var yExtent = fc.extentLinear()
.accessors([d => d.frequency])
.pad([0, 0.1])
.include([0]);
var chart = fc.chartCartesian(
d3.scaleBand(),
d3.scaleLinear()
)
.xDomain(data.map(d => d.letter))
.xPadding(0.2)
.yDomain(yExtent(data))
.yTicks(10, '%')
.yOrient('left')
.svgPlotArea(barSeries);
d3.select('#chart')
.datum(data)
.call(chart);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment