仅供学习之用,效果图如下:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
#container{
width: 800px;
height: 500px;
background: #333;
margin: 0 auto;
}
svg{
background: #fff;
margin: 50px 100px;
}
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: 'Microsoft YaHei';
font-size: 12px;
}
.myrect{
fill: aqua;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
<script>
let datas=[
{
key:"html",
value:"34"
},
{
key:"css",
value:"54"
},
{
key:"javascript",
value:"64"
},
{
key:"java",
value:"85"
},
{
key:"python",
value:"25"
},
{
key:"C++",
value:"49"
}
]
let width=600,height=400,padding=40
let svg=d3.select("#container")
.append("svg")
.attr("width",width)
.attr("height",height)
let xScale=d3.scaleBand()
.domain(datas.map(d=>d.key))
.range([padding,width-2*padding])
.padding(0.5)
let yScale=d3.scaleLinear()
.domain([0,d3.max(datas,(d)=>d.value)])
.range([height-padding*2,0])
let xAxis=d3.axisBottom(xScale)
let yAxis=d3.axisLeft(yScale)
// 绘制坐标轴
svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(0,'+(height-padding)+')')
.call(xAxis)
svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate('+ padding+','+padding+')')
.call(yAxis);
svg.selectAll("rect")
.data(datas)
.enter()
.append("rect")
.attr("x",d=>xScale(d.key))
.attr("y",d=>yScale(d.value)+padding)
.attr("width",xScale.bandwidth())
.attr("height",d=>height-padding*2-yScale(d.value))
.attr("class","myrect")
</script>