效果圖如下:
- 數(shù)據(jù)準備
var dataset=[50,30,60,70,20,80,100];
var xlabel=['0~50','50~100','100~200','200~500','500~1000','1000~2000','>2000'];
- 封裝方法
function drawRect(divId,dataset,xlabel) {
var _svg = d3.select("#"+divId)
.append("svg")
.attr("width","100%")
.attr("height","100%");
var _gAll = _svg.append("g")
.attr("transform","translate(25,25)");
var _gyaxis = _gAll.append("g")
.attr("id","gyaxis")
.attr("transform","translate(50,50)");
var _linescale = d3.scaleLinear()
.domain([0,100]).nice()//nice用來優(yōu)化數(shù)據(jù) 四舍五入等
.range([150,0])//亦可以用rangeRound輸出整數(shù)
.clamp(true);
var _yaxis = d3.axisLeft()
.scale(_linescale)
//.ticks(5)
.tickValues([0,25,50,75,100])
//.tickFormat(d3.format("%"))
;
_yaxis(_gyaxis);
d3.select("#gyaxis")
.selectAll("text")
.attr("fill","blue")
//.style("font-size","24px")
// .style("transform","rotate(-45deg)")
;
d3.select("#gyaxis")
.selectAll("line")
.attr("stroke","blue");
d3.select("#gyaxis")
.selectAll("path")
.attr("stroke","blue");
var _gxaixs = _gAll.append("g")
.attr("id","gxaxis")
.attr("transform","translate(50,200)");
var _bandscale = d3.scaleBand()
.paddingInner(0.2)//20%包括內(nèi)外邊距及段間距paaddingInner只包括段間距
.domain(xlabel)
.range([0,450]);
var _xaxis = d3.axisBottom()
.scale(_bandscale);
_xaxis(_gxaixs);
d3.select("#gxaxis")
.selectAll("text")
.attr("fill","blue")
.style("transform","rotate(-45deg)")
// .attr("dy","34px")
.attr("dx","-34px");
d3.select("#gxaxis")
.selectAll("line")
.style("stroke","blue");
d3.select("#gxaxis")
.selectAll("path")
.style("stroke","blue");
var _gchartarea = _gAll.append("g")
.attr("transform","translate(50,50)");
_gchartarea.append("g")
.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x",function(d,i){
return _bandscale(xlabel[i]);
})
.attr("y",function(d,i){
return 150 - _linescale(100-d);
})
.attr("width",_bandscale.bandwidth())
.attr("height",function(d,i){
return _linescale(100-d);
})
.style("fill","steelblue");
_gchartarea.append("g")
.selectAll("text")
.data(dataset)
.enter()
.append("text")
.attr("x",function(d,i){
return _bandscale(xlabel[i]);
})
.attr("y",function(d,i){
return 150-_linescale(100-d);
})
.attr("dx",_bandscale.bandwidth()/2)
.attr("dy","1em")
.attr("text-anchor","middle")
.text(function(d){return d;})
.attr("fill","white");
d3.select("#gyaxis")
.selectAll("g")
.append("line")
.attr("x1",0)
.attr("y1",0)
.attr("x2",450)
.attr("y2",0)
.attr("stroke","grey")
.attr("stroke-width","0.5");
}
- 調(diào)用方法畫圖
$(function(){drawRect("mychart",dataset,xlabel);});
$(window).resize(function(){
drawRect("mychart",dataset,xlabel);
});