Skip to content

Instantly share code, notes, and snippets.

@michaelowens
Created June 13, 2014 14:19
Show Gist options
  • Save michaelowens/89f8432296edc1aeb9d4 to your computer and use it in GitHub Desktop.
Save michaelowens/89f8432296edc1aeb9d4 to your computer and use it in GitHub Desktop.
d3 bar chart
{"description":"d3 bar chart","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"style.css":{"default":true,"vim":false,"emacs":false,"fontSize":12},"_.md":{"default":true,"vim":false,"emacs":false,"fontSize":12},"config.json":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"fullscreen":false,"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"pingpong","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01,"ajax-caching":true,"inline-console":true,"thumbnail":"http://i.imgur.com/SqK4u89.png"}
var width = 200,
height = 400,
barPadding = 2,
svg, dataset, bars, texts,
scale, xAxis;
svg = d3.select('svg')
.attr('width', width)
.attr('height', height)
.attr('style', 'padding: 15px');
dataset = [
5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25
];
// Scale
scale = d3.scale.linear()
.domain([0, d3.max(dataset)])
.range([0, width]);
// Axis
xAxis = d3.svg.axis()
.scale(scale)
.orient('bottom');
svg.append('g').call(xAxis)
.attr('class', 'axis');
// Bars
bars = svg.selectAll('rect')
.data(dataset).enter().append('rect');
bars
.attr('x', 0)
.attr('y', function (d, i) { return i * ((height - 20) / dataset.length) + 20; })
.attr('width', function (d) { return scale(d); })
.attr('height', (height - 20) / dataset.length - barPadding)
.attr('fill', function (d) { return 'rgb(' + d * 10 + ', 0, 0)'; })
.attr('stroke', 'lime')
.attr('stroke-width', '.5px')
.attr('border-color', 'green')
.attr('border-style', 'solid');
// Texts
texts = svg.append('g').selectAll('text')
.data(dataset).enter().append('text');
texts
.text(function (d) { return d; })
.attr('x', function (d) { return scale(d) - 5; /*(d * 4) - 5;*/ })
.attr('y', function (d, i) { return i * ((height - 20) / dataset.length) + 20 + 13; })
.attr('font-family', 'sans-serif')
.attr('font-size', '12px')
.attr('fill', 'white')
.attr("text-anchor", 'end');
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
.bar {
border: 5px solid red;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment