d3.js 柱状图
对比例尺的温习及第一次实战练习
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>d3_demo4</title> <script src="https://d3js.org/d3.v5.min.js"></script> <style> * { margin: 0; padding: 0; outline: none; } svg { width: 100%; height: 100%; } </style> </head> <body> <svg id="mainsvg"></svg> <script> const svg = d3.select('#mainsvg') const margin = {left: 50, top: 50, right: 50, bottom: 50} /** * 数据data */ const data = [ { name: '小吴', score: 80 }, { name: '小娇', score: 10 }, { name: '小婷', score: 30 }, { name: '小木', score: 60 }, { name: '小袁', score: 90 }, { name: '小何', score: 70 } ] /** * 设置svg的kuan高 */ const width = window.innerWidth - margin.left - margin.right const height = window.innerHeight - margin.top - margin.bottom svg.attr('width', width) svg.attr('height', height) svg.style('background', '#cccccc') /** * 设置x轴和y轴的比例尺 */ const xScale = d3.scaleLinear().domain([0, d3.max(data.map(d => d.score))]).range([0, width]).nice() const yScale = d3.scaleBand().domain(data.map(d => d.name)).range([0, (height - margin.bottom)]).padding(0.1) const g = svg.append('g').attr('transform', `translate(${margin.left}, ${height})`) // 创建x轴和y轴 // x轴 const xAxis = d3.axisBottom(xScale) g.append('g').call(xAxis) // y轴 const yAxis = d3.axisLeft(yScale) g.append('g').call(yAxis).attr('transform', `translate(0, -${height - margin.top})`) // 渲染数据 g.append('g').attr('transform', `translate(0, -${height - margin.top})`).selectAll('rect').data(data) .enter() .append('rect') .attr('width', d => xScale(d.score)) .attr('height', yScale.bandwidth()) .attr('fill', '#28caff') .attr('y', d => yScale(d.name)) .attr('opacity', 0.6)
// 设置x轴和y轴的字体样式
d3.selectAll('.tick text').attr('font-size', '1.5em').attr('color', 'purple')
</script> </body> </html>