Skip to content

Instantly share code, notes, and snippets.

@milafrerichs
Last active August 16, 2019 13:25
Show Gist options
  • Save milafrerichs/16766cc7cfd95226d78336bd8fbc2436 to your computer and use it in GitHub Desktop.
Save milafrerichs/16766cc7cfd95226d78336bd8fbc2436 to your computer and use it in GitHub Desktop.
Dynamic Bar Chart
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
.container {
width: 100%;
text-align: center;
}
svg {
margin-top: 40px;
}
.bar { stroke: white; }
</style>
</head>
<body>
<div class="container">
<svg width="450" height="50"></svg>
</div>
<script>
const svg = d3.select('svg');
const width = +svg.attr('width');
const height = +svg.attr('height') / 2;
const g = svg.append('g');
const n = width / 3;
const minY = 0.2;
const maxHue = 360;
const hueDelta = maxHue / n;
const keys = [...Array(n).keys()];
const xScale = d3.scaleBand()
.rangeRound([0, width])
.domain(keys);
const yScale = d3.scaleLinear()
.rangeRound([height, 0])
.domain([0, 1 + minY]);
const draw = (data) => {
g.selectAll('.bar')
.data(data)
.join('rect')
.attr('class', 'bar')
.attr('fill', (v, i) => `hsla(${(i - round) * hueDelta}, 100%, 50%, 1)`)
.attr('x', (_, i) => xScale(i))
.attr('y', v => yScale(v + minY))
.attr('width', xScale.bandwidth())
.attr('height', v => 2 * (height - yScale(v + minY)));
};
let round = 0;
let data = keys.map((_, i) => 0);
setInterval(() => {
data = data.map(v => {
let newV = v;
if (v === 1) { newV = v - 0.1; }
else if (v === 0) { newV = v + 0.1; }
else {
const random = Math.random();
newV = random < 0.5 ? v - 0.1 : v + 0.1;
}
return Math.round(newV * 10) / 10;
});
round = round === (maxHue - 1) ? 0 : round + 1;
draw(data);
}, 100);
draw(data);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment