An example of running bar chart with changing colors.
forked from gnykka's block: Dynamic Bar Chart
forked from vikkya's block: Dynamic Bar Chart
license: mit |
An example of running bar chart with changing colors.
forked from gnykka's block: Dynamic Bar Chart
forked from vikkya's block: Dynamic Bar Chart
<!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> |