使用D3绘制图表(6)--竖直柱状图表

  竖直柱状图的绘制是在水平柱状图的基础上修改的。

  1.html代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <div id="container"></div>
    </body>
    <script type="text/javascript" src="js/d3.js" ></script>
    <script type="text/javascript" src="js/shuzhuangtu.js" ></script>
</html>

  2.js代码

var data = [1,3,4,6,2,9,7,3,8],
bar_width = 50,
bar_padding = 10,
svg_height = 500,
svg_width = (bar_width +bar_padding)*data.length;

var scale = d3.scale.linear()
.domain([0, d3.max(data)])
.range([svg_height, 0]);


var svg = d3.select("#container")
.append("svg")
.attr("width", svg_width)
.attr("height", svg_height)


var bar = svg.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform",function(d, i){return "translate("+i*(bar_width+bar_padding)+", 0)"})

bar.append("rect")
.attr({
    "y":function(d){return scale(d);},
    "width":bar_width,
    "height":function(d){return svg_height-scale(d);}
})
.style("fill","cornflowerblue")

bar.append("text")
.text(function(d){return d;})
.attr({
    "y":function(d){return scale(d)},
    "x":bar_width/2,
    "dy":15,
    "text-anchor":"middle"
})

  3.运行效果

 

posted @ 2016-06-17 12:55  王甘林  阅读(770)  评论(1编辑  收藏  举报