可视化数据分析(三) 一个简单的散点图的实现

代码如下:

<!DOCTYPE>
<html>
<meta charset="utf-8">
<style> text{ font: 10px sans-serif; } .axis path, .axis line{ fill: none; stroke: black; shape-rendering: crispEdges; } </style>
<body>
    <h1>The scatter diagram</h1>
    <script src="d3/d3.v3.js"></script>
    <script> //散点图的圆心的位置 var center =[ [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], [0.6,0.7] ]; //设置坐标轴的横轴和纵轴的长度 var xAxisWidth = 400; var yAxisWidth = 400; //生成svg图 var width = 550; var height = 550; var svg = d3.select("body") .append("svg") .attr("width" , width ) .attr("height", height ); //设置外边距 var padding = { top:30, right:30, bottom:30, left:30 }; </script>

    <script> function draw() { //设置比例尺 var xScale = d3.scale.linear() .domain([0,1.2*d3.max(center,function(d){ return d[0]; })]) .range([0,xAxisWidth]); var yScale = d3.scale.linear() .domain([0,1.2*d3.max(center,function(d){ return d[1]; })]) .range([yAxisWidth,0]); //画坐标轴 svg.selectAll("g").remove(); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom"); svg.append("g") .attr("class","axis") .attr("transform","translate(" + padding.left+ ","+(height-padding.bottom) + ")" ) .call(xAxis); var yAxis = d3.svg.axis() .scale(yScale) .orient("left"); svg.append("g") .attr("class","axis") .attr("transform","translate(" + padding.left + ","+(height-yAxisWidth-padding.top) + ")" ) .call(yAxis); //描点 var circle = svg.selectAll("circle") .data(center) .enter() .append("circle") .attr("fill","black") .attr("cx",function(d){ return padding.left + xScale(d[0]); }) .attr("cy",function(d){ return height-padding.bottom -yScale(d[1]); }) .attr("r",5) .transition() .attr("fill","gray") .duration(1000) .delay(500); } </script>

    <script> draw(); </script>
    <br>
    <button type="button" onclick="add()">添加一个点</button>
    <script> function add() { center.push([Math.random(),Math.random()]); ` draw(); } </script>
</body>

</html>

效果图如下:

你可能感兴趣的:(数据分析,可视化)