Skip to content

Instantly share code, notes, and snippets.

@Robert-W
Last active August 15, 2016 03:09
Show Gist options
  • Save Robert-W/709734bab87de226c226ed74ecbef973 to your computer and use it in GitHub Desktop.
Save Robert-W/709734bab87de226c226ed74ecbef973 to your computer and use it in GitHub Desktop.
D3 4.0 Bar Chart
.chart {
position: relative;
}
.tooltip {
position: absolute;
background: blue;
color: white;
padding: 5px;
top: 20px;
}
.bar {
fill: steelblue;
}
.bar:hover {
fill: red;
}
.axis {
font: 10px sans-serif;
fill: black;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
var data = [
{ key: 'A', value: 12 },
{ key: 'B', value: 2 },
{ key: 'C', value: 24 },
{ key: 'D', value: 36 },
{ key: 'E', value: 15 },
{ key: 'F', value: 18 },
{ key: 'G', value: 21 },
{ key: 'H', value: 11 },
{ key: 'I', value: 7 }
];
var margin = { top: 20, right: 20, bottom: 30, left: 40 };
var height = 400 - margin.top - margin.bottom;
var width = 400 - margin.right - margin.left;
//- X Scale
var x = d3.scaleBand()
.rangeRound([0, width], .1);
//- Y Scale
var y = d3.scaleLinear()
.range([height, 0]);
//- Axis
var xAxis = d3.axisBottom().scale(x);
var yAxis = d3.axisLeft().scale(y).ticks(10);
var chart = d3.select('.chart');
//- Chart body
var svg = chart
.append('svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//- Tooltip
var tooltip = chart
.append('div')
.attr('class', 'tooltip');
//- Domains
x.domain(data.map(function (d) { return d.key; }));
y.domain([0, d3.max(data, function (d) { return d.value; })]);
//- X Axis
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0, ' + height + ')')
.call(xAxis);
//- Y Axis
svg.append('g')
.attr('class', 'y axis')
.call(yAxis)
.append('text')
.attr('transform', 'rotate(-90)')
.attr('y', 6)
.attr('dy', '.71em')
.style('text-anchor', 'end')
.text('Value');
//- Bar Chart
svg.selectAll('.bar')
.data(data)
.enter()
.append('rect')
.attr('class', 'bar')
.attr('x', function (d) { return x(d.key) + 3; })
.attr('width', x.step() - 6)
.attr('y', function (d) { return y(d.value); })
.attr('height', function (d) { return height - y(d.value); });
//- Events
svg.selectAll('.bar')
.on('mouseover', function (d) {
var elX = +d3.event.target.getAttribute('x') + x.step() + 6;
tooltip.html(d.value).style('left', elX + 'px');
});
@Robert-W
Copy link
Author

Robert-W commented Aug 15, 2016

Assumes a <div class='chart'></div> exists. Styling is ugly but there to demonstrate basic setup. See working example here: https://jsfiddle.net/3jrLj4ua/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment