Skip to content

Instantly share code, notes, and snippets.

@ColinEberhardt
Last active May 28, 2019 14:50
Show Gist options
  • Save ColinEberhardt/ab37d7973bfe32feea8cad21bd40fe1a to your computer and use it in GitHub Desktop.
Save ColinEberhardt/ab37d7973bfe32feea8cad21bd40fe1a to your computer and use it in GitHub Desktop.
Let's build a bar chart - d3fc canvas version
license: mit
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;
}
</style>
<div id="chart"></div>
<script type='text/babel'>
const isVowel = (letter) => 'AEIOU'.indexOf(letter) !== -1;
var barSeries = fc.autoBandwidth(fc.seriesCanvasBar())
.crossValue(d => d.letter)
.align('left')
.mainValue(d => d.frequency)
.decorate((context, datum) => {
context.textAlign = 'center';
context.fillStyle = '#000';
context.font = '12px Arial';
context.fillText(d3.format('.1%')(datum.frequency), 0, -8);
context.fillStyle = isVowel(datum.letter) ? 'indianred' : 'steelblue';
});
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.1)
.yDomain(yExtent(data))
.yTicks(10, '%')
.yOrient('left')
.canvasPlotArea(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