使用D3绘制图表(5)--水平柱状图表

时间:2022-08-02 05:55:48

  绘制水平柱状图表的方法也不是很难,首先在svg中插入g,然后在g中插入rect。

  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_height = 50,
bar_padding = 10,
svg_width = 500,
svg_height = (bar_height +bar_padding)*data.length;

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


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(0, "+i*(bar_height+bar_padding)+")"})

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

bar.append("text")
.text(function(d){return d;})
.attr({
    "x":function(d){return scale(d)},
    "y":bar_height/2,
    "text-anchor":"end"
})

  3.运行效果

使用D3绘制图表(5)--水平柱状图表