1. 程式人生 > >D3.js-散點圖

D3.js-散點圖

var dataset = [[0.5, 0.5],[0.7, 0.8],[0.4, 0.9], [0.11, 0.32],[0.88, 0.25],[0.75, 0.12], [0.5, 0.1],[0.2, 0.3],[0.4, 0.1]]; var width = 400; // 可視區域寬度 var height = 400; // 可視區域高度 var xAxisWidth = 300; // x軸寬度 var yAxisWidth = 300; // y軸寬度 var
padding = {top: 20, right: 20, bottom:20, left:50}; var svg = d3.select("body").select("#content") .append("svg") .attr("width", width).attr("height", height); /*定義比例尺*/ var xScale = d3.scale.linear() .domain([0, 1]) .range([0
, xAxisWidth]); var yScale = d3.scale.linear() .domain([0, 1]) .range([0, yAxisWidth]); /* 繪製圓點 */ function drawCircle(){ var circleUpdate = svg.selectAll("circle").data(dataset); // update處理 circleUpdate.transition().duration(500
) .attr("cx", function(d){ return padding.left + xScale(d[0]); }) .attr("cy", function(d, i){ return height - padding.bottom - yScale(d[1]); }) .attr("r", 5); // enter處理 circleUpdate.enter().append("circle") .attr("cx", function(d){ return padding.left; }) .attr("cy", function(d, i){ return height - padding.bottom; }) .attr("r", 5) .transition().duration(500) .attr("cx", function(d, i){ return padding.left + xScale(d[0]); }) .attr("cy", function(d, i){ return height - padding.bottom - yScale(d[1]); }); // exit處理 circleUpdate.exit() .transition().duration(500) .attr("fill", "white") .remove(); } /* 新增座標軸 */ function drawScale(){ var xAxis = d3.svg.axis().scale(xScale).orient("bottom"); yScale.range([yAxisWidth, 0]); // 重新設定y軸比例尺的值域,與原來的相反 var yAxis = d3.svg.axis().scale(yScale).orient("left"); svg.append("g").attr("class", "axis") .attr("transform", "translate("+ padding.left +","+ (height - padding.bottom) +")") .call(xAxis); svg.append("g").attr("class", "axis") .attr("transform", "translate("+ padding.left +","+ (height - padding.bottom - yAxisWidth) +")") .call(yAxis); // 繪製完比例尺,還原比例尺y軸值域 yScale.range([0, yAxisWidth]); } // 初始化 window.addEventListener("load", function(){ drawCircle(); drawScale(); }); var toFixed = Number.prototype.toFixed; /* 更新 */ function update(){ for(var i = 0, len = dataset.length; i < len; i++){ dataset[i][0] = +toFixed.call(Math.random(), 2); dataset[i][1] = +toFixed.call(Math.random(), 2); } drawCircle(); } /* 增加 */ function add(){ dataset.push([+toFixed.call(Math.random(), 2), +toFixed.call(Math.random(), 2)]); drawCircle(); } /* 刪除 */ function sub(){ dataset.pop(); drawCircle(); }