Create a gist now

Instantly share code, notes, and snippets.

@pshihn /README.md
Last active Jan 25, 2017

What would you like to do?
Sketchy Bar Chart
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">
<canvas></canvas>
<script src="//d3js.org/d3.v4.0.0-alpha.4.min.js"></script>
<script src="//roughjs.com/builds/rough.min.js"></script>
<script>
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d");
rough = new RoughCanvas(canvas, 960, 500);
rough.fill = "steelblue";
rough.hachureGap = 2;
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = canvas.width - margin.left - margin.right,
height = canvas.height - margin.top - margin.bottom;
var x = d3.scaleBand()
.rangeRound([0, width])
.padding(0.1);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
context.translate(margin.left, margin.top);
d3.requestTsv("data.tsv", function(d) {
d.frequency = +d.frequency;
return d;
}, function(error, data) {
if (error) throw error;
x.domain(data.map(function(d) { return d.letter; }));
y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
var yTickCount = 10,
yTicks = y.ticks(yTickCount),
yTickFormat = y.tickFormat(yTickCount, "%");
data.forEach(function(d) {
rough.rectangle(x(d.letter), y(d.frequency), x.bandwidth(), height - y(d.frequency));
});
// since we are going to draw on canvas directly, i.e using context2d and not rough.js,
// we call requestAnimationFrame. This will prevent our drawing to be cleared by rough.js
window.requestAnimationFrame(function() {
context.beginPath();
x.domain().forEach(function(d) {
context.moveTo(x(d) + x.bandwidth() / 2, height);
context.lineTo(x(d) + x.bandwidth() / 2, height + 6);
});
context.strokeStyle = "black";
context.stroke();
context.textAlign = "center";
context.textBaseline = "top";
x.domain().forEach(function(d) {
context.fillText(d, x(d) + x.bandwidth() / 2, height + 6);
});
context.beginPath();
yTicks.forEach(function(d) {
context.moveTo(0, y(d) + 0.5);
context.lineTo(-6, y(d) + 0.5);
});
context.strokeStyle = "black";
context.stroke();
context.textAlign = "right";
context.textBaseline = "middle";
yTicks.forEach(function(d) {
context.fillText(yTickFormat(d), -9, y(d));
});
context.beginPath();
context.moveTo(-6.5, 0 + 0.5);
context.lineTo(0.5, 0 + 0.5);
context.lineTo(0.5, height + 0.5);
context.lineTo(-6.5, height + 0.5);
context.strokeStyle = "black";
context.stroke();
context.save();
context.rotate(-Math.PI / 2);
context.textAlign = "right";
context.textBaseline = "top";
context.font = "bold 10px sans-serif";
context.fillText("Frequency", -10, 10);
context.restore();
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment