D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
skimlik
Full window
Github gist
Simple Blocks
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v5.min.js"></script> <style> body { margin: 2em; } .svg-bar { stroke: steelblue; fill: steelblue; } .plot-area { fill: transparent; } .tick line{ opacity: 0.2; stroke: #9b9999; } .axis--x path { stroke: steelblue; stroke-width: 1.5px; } .axis--y path { display: none; } .svg-bar:hover { fill: lightblue; stroke: lightblue; } </style> </head> <body> <script> // Feel free to change or delete any of the code you see in this editor! var h = 480; var w = 960; var svg = d3.select("body").append("svg") .attr("width", w) .attr("height", h) var data = [ 10, 15, 17, 12, 14, 11, 17, 18, 10, 1, 5, 8 ]; var margins = { top: 20, right: 60, bottom: 30, left: 20}; var height = (h - (margins.top + margins.bottom)); var width = (w - (margins.left + margins.right)); var yScale = d3.scaleLinear() .domain([data.length, 0]) .rangeRound([margins.top , height]) .nice(); var xScale = d3.scaleLinear() .domain([0, d3.max(data, function(d) {return d;})]) .rangeRound([margins.left, width]); //.nice(); var xAxis = d3.axisBottom(xScale) .tickSizeInner(-height + margins.top) .tickPadding(10); var yAxis = d3.axisLeft(yScale) .ticks(data.length) .tickPadding(5); var plot = svg.append('g') .attr('class', 'plot-area') .attr('transform', 'translate(0, '+ margins.top+')'); plot.append('g') .attr('class', 'axis axis--x') .attr('transform', 'translate(0, '+ height +')') .call(xAxis); plot.append('g') .attr('class', 'axis axis--y') .attr('transform', 'translate('+margins.left+', 0)') .call(yAxis); var barCount = data.length; var barScale = d3.scaleLinear() .range([margins.top, height - margins.top - margins.bottom]) .domain([0, barCount - 1]); var barHeight = barCount > 1 ? barScale(1) - barScale(0) - 5 : height - 30; var bars = plot .selectAll('.svg-bar') .data(data) .enter(); bars.append('rect') .classed('svg-bar', true) .attr('x', margins.left) .attr('y', function(_, ix) { return barScale(ix); }) .attr('width', function(d) { return xScale(d);}) .attr('height', barHeight); bars.append('text').text(function(d) { return d; }) .attr('x', function(d) { return xScale(d / 2);}) .attr('y', function(_, ix) { return barScale(ix) + barHeight / 2;}) .style('font-size', 14) .style('font-weight', 'bold') .style('font-family', 'monospace'); </script> </body>
https://d3js.org/d3.v5.min.js