d3.js-坐标轴

xiaoxiao2021-02-28  86

旧版本: var axis = d3.svg.axis() .scale(linear) //指定比例尺 .orient("bottom") //指定刻度的方向 .ticks(7); //指定刻度的数量 最新版: var axis = d3.axisBottom(linear) .ticks(7); //指定刻度的数量

在svg中放入坐标

svg.append("g") .attr("class","axis") .attr("transform","translate(20,130)") .call(axis);

完整代码:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="lib/d3.js"></script> </head> <body> </body> <script> var width = 300; //画布的宽度 var height = 300; //画布的高度 var svg = d3.select("body") //选择文档中的body元素 .append("svg") //添加一个svg元素 .attr("width", width) //设定宽度 .attr("height", height); //设定高度 var dataset = [ 2.50 , 2.10 , 1.70 , 1.30 , 0.90 ]; //数据(表示矩形的宽度) var rectHeight = 25; //每个矩形所占的像素高度(包括空白) // 比例尺 var linear = d3.scaleLinear() .domain([0, d3.max(dataset)]) .range([0, 250]); var axis = d3.axisBottom(linear) .ticks(7); //指定刻度的数量 svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("x",20) .attr("y",function(d,i){ return i * rectHeight; }) .attr("width",function(d){ return linear(d); }) .attr("height",rectHeight-2) .attr("fill","steelblue"); svg.append("g") .attr("class","axis") .attr("transform","translate(20,130)") .call(axis); </script> <style> .axis path, .axis line{ fill: none; stroke: black; shape-rendering: crispEdges; } .axis text { font-family: sans-serif; font-size: 11px; } </style> </html>
转载请注明原文地址: https://www.6miu.com/read-84319.html

最新回复(0)