d3.js


<html>
<head>
<meta charset="utf-8">
<title>完整的柱形圖</title>
</head> html

<style>
.axis path,
.axis line{
fill: none;
stroke: black;
shape-rendering: crispEdges;
}數組

.axis text {
font-family: sans-serif;
font-size: 11px;
}app

.MyRect {
fill: steelblue;
}dom

.MyText {
fill: white;
text-anchor: middle;
}
</style>svg

<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>orm

//畫布大小
var width = 400;
var height = 400;htm

//在 body 裏添加一個 SVG 畫布
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);ip

//畫布周邊的空白
var padding = {left:30, right:30, top:20, bottom:20};utf-8

//定義一個數組
var dataset = [10, 20, 30, 40, 33, 24, 12, 5];

//x軸的比例尺
var xScale = d3.scale.ordinal()
.domain(d3.range(dataset.length))
.rangeRoundBands([0, width - padding.left - padding.right]);it

//y軸的比例尺
var yScale = d3.scale.linear()
.domain([0,d3.max(dataset)])
.range([height - padding.top - padding.bottom, 0]);

//定義x軸
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");

//定義y軸
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");

//矩形之間的空白
var rectPadding = 4;

//添加矩形元素
var rects = svg.selectAll(".MyRect")
.data(dataset)
.enter()
.append("rect")
.attr("class","MyRect")
.attr("transform","translate(" + padding.left + "," + padding.top + ")")
.attr("x", function(d,i){
return xScale(i) + rectPadding/2;
} )
.attr("y",function(d){
return yScale(d);
})
.attr("width", xScale.rangeBand() - rectPadding )
.attr("height", function(d){
return height - padding.top - padding.bottom - yScale(d);
});

//添加文字元素
var texts = svg.selectAll(".MyText")
.data(dataset)
.enter()
.append("text")
.attr("class","MyText")
.attr("transform","translate(" + padding.left + "," + padding.top + ")")
.attr("x", function(d,i){
return xScale(i) + rectPadding/2;
} )
.attr("y",function(d){
return yScale(d);
})
.attr("dx",function(){
return (xScale.rangeBand() - rectPadding)/2;
})
.attr("dy",function(d){
return 20;
})
.text(function(d){
return d;
});

//添加x軸
svg.append("g")
.attr("class","axis")
.attr("transform","translate(" + padding.left + "," + (height - padding.bottom) + ")")
.call(xAxis);

//添加y軸
svg.append("g")
.attr("class","axis")
.attr("transform","translate(" + padding.left + "," + padding.top + ")")
.call(yAxis);

</script> </body> </html>

相關文章
相關標籤/搜索