本人的个人博客为: www.ourd3js.com
csdn博客为: blog.csdn.net/lzhlzz
转载请注明出处,谢谢。
前面几节讲解了图标、坐标轴、比例等等,这一节整合这些内容做一个实用的图表。结果图如下:
代码如下所示:
<html> <head> <meta charset="utf-8"> <title>Chart</title> </head> <style> .axis path, .axis line{ fill: none; stroke: black; shape-rendering: crispEdges; } .axis text { font-family: sans-serif; font-size: 11px; } </style> <body> <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> <script> var width = 600; var height = 600; var dataset = []; var num = 15; //数组的数量 for(var i = 0; i < num ; i++){ var tempnum = Math.floor( Math.random() * 50 ); // 返回 0~49 整数 dataset.push(tempnum); } var svg = d3.select("body").append("svg") .attr("width",width) .attr("height",height); var xAxisScale = d3.scale.ordinal() .domain(d3.range(dataset.length)) .rangeRoundBands([0,500]); var yAxisScale = d3.scale.linear() .domain([0,d3.max(dataset)]) .range([500,0]); var xAxis = d3.svg.axis() .scale(xAxisScale) .orient("bottom"); var yAxis = d3.svg.axis() .scale(yAxisScale) .orient("left"); var xScale = d3.scale.ordinal() .domain(d3.range(dataset.length)) .rangeRoundBands([0,500],0.05); var yScale = d3.scale.linear() .domain([0,d3.max(dataset)]) .range([0,500]); svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("x", function(d,i){ return 30 + xScale(i); } ) .attr("y",function(d,i){ return 50 + 500 - yScale(d) ; }) .attr("width", function(d,i){ return xScale.rangeBand(); }) .attr("height",yScale) .attr("fill","red"); svg.selectAll("text") .data(dataset) .enter().append("text") .attr("x", function(d,i){ return 30 + xScale(i); } ) .attr("y",function(d,i){ return 50 + 500 - yScale(d) ; }) .attr("dx", function(d,i){ return xScale.rangeBand()/3; }) .attr("dy", 15) .attr("text-anchor", "begin") .attr("font-size", 14) .attr("fill","white") .text(function(d,i){ return d; }); svg.append("g") .attr("class","axis") .attr("transform","translate(30,550)") .call(xAxis); svg.append("g") .attr("class","axis") .attr("transform","translate(30,50)") .call(yAxis); </script> </body> </html>
[5.1] D3.js中整合坐标轴 - 图表 - 文字标签,布布扣,bubuko.com
原文地址:http://blog.csdn.net/lzhlzz/article/details/34429675