1.普通的bar chart示例:
<html> <head></head> <body> <h1>BarChart</h1> <svg width="1300" height="600" id="mainsvg" class="svgs"></svg> </body> </html> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js" type="text/javascript"></script> <script type="text/javascript"> const data = [{name:"Jack",value:6},{name:"Mike",value:6},{name:"Lucy",value:7},{name:"Coco",value:8}]; const svg = d3.select("#mainsvg"); const width = +svg.attr('width'); const height = +svg.attr("height"); const margin = {top:60,right:30,bottom:60,left:150}; const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; const xScale = d3.scaleLinear() .domain([0,d3.max(data,d=>d.value)]) .range([0,innerWidth]); const yScale = d3.scaleBand() .domain(data.map(d=>d.name)) .range([0,innerHeight]) .padding(0.1); const g = svg.append('g').attr('id','maingroup').attr('transform',`translate(${margin.left},${margin.right})`); const yAxis = d3.axisLeft(yScale); g.append('g').call(yAxis); const xAxis = d3.axisBottom(xScale); g.append('g').call(xAxis).attr('transform',`translate(0,${innerHeight})`); data.forEach(d=>{ g.append('rect') .attr('width',xScale(d.value)) .attr('height',yScale.bandwidth()) .attr('fill','green') .attr('opacity',0.7) .attr('y',yScale(d.name)) }); d3.selectAll(".tick text").attr('font-size','2em'); g.append("text").text("Member") .attr('font-size','2em') .attr('transform',`translate(${innerWidth/2},0)`) .attr('text-anchor','middle') </script>