JSFiddle - React, Tailwind, and code Playground
HTML
<div id="result"></div>
<input type="button" value="Add Data" />
<input type="reset" value="Reset" />
CSS
svg {
border: 1px solid black;
}
.axis line, .axis path{
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
rect.data {
fill: steelblue;
}
JavaScript
var myData = [], // Bar chart's data source
max = 10, // Y-axis maximum value
margin = {top: 20, right: 20, bottom: 40, left: 40},
width = 400, height = 300
function randData(){ // Add random number to myData
myData.push(Math.ceil(Math.random() * max));
}
function resetData(){ // Reset myData
myData = [];
}
// Tha setting of the bar chart
var y = d3.scale.linear() // Scale of y coordinate
.domain([0, max])
.range([height-margin.bottom, margin.top]);
var h = d3.scale.linear() // Scale of height
.domain([0, max])
.range([0, height-margin.top-margin.bottom]);
var svg = d3.select('#result').append('svg') // Create <SVG> HTML Element
.attr('width', width)
.attr('height', height);
var xAxisLine = svg.append('g') // Create X-axis line
.attr('class', 'axis')
.append('line')
.attr('x1', margin.left)
.attr('y1', height - margin.bottom)
.attr('x2', width - margin.right)
.attr('y2', height - margin.bottom);
var yAxis = d3.svg.axis() // D3 axis object
.scale(y)
.orient("left");
var yAxisLine = svg.append("g") // Create Y-axis line
.attr('class', 'axis')
.attr("transform", "translate("+margin.left+",0)")
.call(yAxis);
// Main function to draw the bar chart's "bars"
function render(){
var x = d3.scale.ordinal() // Create scale of X-axis
.domain(myData.map(function(d, i){ return i; }))
.rangeRoundBands([margin.left, width-margin.right], 0.1);
var bar = svg.selectAll('.data') // Bind data
.data(myData);
bar.enter().append('rect') // Data enter
.attr('class', 'data')
.attr("width", x.rangeBand())
.attr("height", h(0))
.attr('x', function(d, i){ return x(i); })
.attr('y', y(0));
bar.transition() // Data update
.duration(1000)
.attr("height", h)
.attr("width", x.rangeBand())
.attr('x', function(d, i){ return x(i); })
.attr('y', y);
...