Skip to content

Instantly share code, notes, and snippets.

@fokot
Created May 2, 2016 14:46
Show Gist options
  • Save fokot/439c379c510f42fb1ec954fea4885c20 to your computer and use it in GitHub Desktop.
Save fokot/439c379c510f42fb1ec954fea4885c20 to your computer and use it in GitHub Desktop.
D3 barchart
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar {
fill: steelblue;
}
.x.axis path {
fill: none;
stroke: #C8C8C8;
stroke-width: 2;
}
.bar-tooltip {
background: #eee;
box-shadow: 0 0 5px #999999;
color: #333;
display: none;
font-size: 12px;
color: black;
left: 500px;
opacity: 1;
padding: 10px;
position: absolute;
text-align: center;
top: 80px;
width: 80px;
z-index: 10;
}
svg {
border: solid red 1px;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
const data = [
['A', 8],
['B', 7],
['C', 5],
['D', 10],
['E', 7],
['F', 9],
];
const padding = .1;
const VIEWPORT_WIDTH = 800;
const VIEWPORT_HEIGHT = 300;
const BOTTOM_BORDER = 30;
const barChart = d3.select(document.body);
const x = d3.scale.ordinal()
.rangeRoundBands([0, VIEWPORT_WIDTH], padding ? padding : .1);
const y = d3.scale.linear()
.range([VIEWPORT_HEIGHT, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(0, 0);
const svg = barChart.append("svg")
.attr('width', '100%')
.attr('height', '100%')
.attr('viewBox', `0 0 ${VIEWPORT_WIDTH} ${VIEWPORT_HEIGHT + BOTTOM_BORDER}`)
.attr('preserveAspectRatio', 'xMaxYMax');
x.domain(data.map(d => d[0]));
y.domain([0, d3.max(data, d => d[1])]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + VIEWPORT_HEIGHT + ")")
.call(xAxis);
const bars = svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", d => x(d[0]))
.attr("width", x.rangeBand())
.attr("y", d => y(d[1]))
.attr("height", d => VIEWPORT_HEIGHT - y(d[1]));
// Tooltips
const tooltip = barChart
.append('div')
.attr('class', 'bar-tooltip');
tooltip.append('div')
.attr('class', 'bar-label');
tooltip.append('div')
.attr('class', 'bar-count');
bars.on('mouseover', d => {
tooltip.select('.bar-label').html(d[0]);
tooltip.select('.bar-count').html(d[1]);
tooltip.style('display', 'block');
});
bars.on('mouseout', () => tooltip.style('display', 'none'));
bars.on('mousemove', () =>
tooltip.style('top', (d3.event.pageY + 10) + 'px')
.style('left', (d3.event.pageX + 10) + 'px')
);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment