87,921
社区成员
发帖
与我相关
我的任务
分享
<html>
<head>
<meta charset="GBK">
<title>单元小结</title>
<script type="text/javascript" src="d3.js"></script>
<!--设定坐标轴的样式和位置-->
<style>
.axis path,
.axis line{
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
</style>
</head>
<body>
<script type="text/javascript">
//1.准备数据
var index = [123 , 78 , 43 , 23 , 99 , 54];
var color = ["red", "blue", "green", "yellow", "black" , "orange"];
//2.准备画布
var width = 400;
var heigth = 400;
var svg = d3.select("body")
.append("svg")
.attr("width" , width)
.attr("heigth" , heigth);
var max = d3.max(index);
var min = d3.min(index);
//2.1画布周边的空白
var padding = {left:30, right:30, top:20, bottom:20};
//3.准备线性比例尺
var linear = d3.scale.linear()
.domain([min , max])
.range([0 , 200]);
//4.准备序数比例尺
var ordinal = d3.scale.ordinal()
.domain(index)
.range(color);
//5.准备坐标轴
var axis = d3.svg.axis()
.scale(linear)
.orient("bottom")
.ticks(7);
//6.设置坐标轴颜色、位置、标签
svg.append("g")
.attr("class" , "axis")
.attr("transform" , "translate(15 , 150)")
.call(axis);
//7.每个矩形所占的像素高度(包括空白)
var rectHeigth = 25;
//8.做图表
svg.selectAll("rect") //先查找到rect矩阵,然后在添加
.data(index)
.enter()
.append("rect")
.attr("x" , 15)
.attr("y" , function(d , i){
return i * rectHeigth;
})
.attr("width" , function(d){
return linear(d);
})
.attr("heigth" , rectHeigth-2 )
.attr("fill" , function(d){
return ordinal(d);
});
</script>
</body>
</html>