柱狀圖的組成部分 : 矩形,x軸,y軸,比例尺,數(shù)據(jù)
- 可改變x軸,y軸樣式
- 可改變數(shù)值樣式
- 帶鼠標事件
最終實現(xiàn)效果
//html部分
<svg><svg>
//css部分
.axis path,.axis line{
fill: none;
stroke: red;
stroke-width: 3px;
shape-rendering: crispEdges;
}
.axis text{
font-family: sans-serif;
font-size:14px;
stroke:aqua;
}
//js部分
const dataset = [
{"text":"iphone4","value":200},
{"text":"iphone5","value":300},
{"text":"iphone6","value":500},
{"text":"iphone7","value":100},
{"text":"iphone8","value":120},
]
const svgWidth = 400
const svgHeight = 400
const padding = {top:20,bottom:20,left:40,right:40}
//1.繪制畫布
const svg = d3.select("svg")
.attr("width",svgWidth)
.attr("height",svgHeight)
//2.設置比例尺
const xdate = []
const ydate = []
const xAxisLength = svgWidth-padding.left-padding.right
const yAxisLength = svgHeight-padding.top-padding.bottom
for( let i of dataset){
xdate.push(i.text)
ydate.push(i.value)
}
const xScale = d3.scaleBand() // x軸的對應關系 : ["iphone4","iphone5","iphone6","iphone7","iphone8"] <----->[0,xAxisLength] 應使用 序數(shù)段比例尺d3.scaleBand()
.domain(xdate)
.range([0,xAxisLength])
const yScale = d3.scaleLinear() // y軸的對應關系 : [0,d3.max(ydate)] <----->[yAxisLength, 0] 應使用 線數(shù)比例尺d3.scaleLinear()
.domain([0,d3.max(ydate)])
.range([yAxisLength,0])
const _yScale = d3.scaleLinear()
.domain([0,d3.max(ydate)])
.range([0,yAxisLength])
//3.繪制矩形
const rectGap = 20
const rect = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x",(d,i)=>{
return xScale.bandwidth() * i + rectGap/2
})
.attr("y",(d,i)=>{
return yScale(d.value)
})
.attr("width",xScale.bandwidth()-rectGap)
.attr("height",(d,i)=>{
return _yScale(d.value)
})
.attr("transform", "translate(" + padding.left + "," + padding.top + ")")
.attr("fill","red")
//4.展示數(shù)據(jù)
svg.selectAll('text')
.data(dataset)
.enter()
.append('text')
.attr("transform", "translate(" + padding.left + "," + padding.top + ")")
.attr("text-anchor", "middle")
.attr('x', (d, i) => {
return xScale.bandwidth() * i + rectGap/2
})
.attr('y', (d, i) => {
return yScale(d.value)
})
.attr("dx", function() {
return (xScale.bandwidth() - rectGap)/2;
})
.attr("dy", 20)
.attr("stroke","blue")
.text((d) => d.value)
//5.繪制坐標軸
const xAxis = d3.axisBottom(xScale)
const yAxis = d3.axisLeft(yScale)
svg.append("g").attr("transform", "translate(" + padding.left + ", " + (svgHeight-padding.top) + ")")
.attr("class","axis")
.call(xAxis)
svg.append("g").attr("transform", "translate(" + padding.left + ", " + padding.top + ")")
.attr("class","axis")
.call(yAxis)
//6.鼠標事件
svg.selectAll('rect')
.on("mouseover",function(d,i){
d3.select(this)
.transition()
.duration(100)
.attr("fill","yellow")
})
.on("mouseout",function(d,i){
d3.select(this)
.transition()
.duration(500)
.attr("fill","red")
})