d3v4制作可以自动变化的柱形图
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> D3Template</title>
<!-- <script src="https://d3js.org/d3.v4.min.js"></script>-->
<script type="text/javascript" src="d3.v4.js"></script>
</head>
<body>
<button id ='auto'>start</button>
<script type="text/javascript">
//坐标
var data2=d3.range(30).map(function(a,b){
a=Math.round(Math.random()*500),
b=Math.round(Math.random()*200)
return [a,b]})
//键值对
var data3=d3.range(30).map(function(a,b){
a=a++;
b=Math.round(Math.random()*100)
return {key:a,value:b};
})
console.log(data3)
console.log(data2)
//d3.select('body')
// .selectAll('p')
// .data(data3)
// .enter()
// .append('p')
// .text(function(d){return 'value:'+d.value})
var xScale,yScale,xAixs,yAxis
var dataset=[]
var xmark=[]
var w=500,h=200
var svg=d3.select("body")
.append("svg")
.attr("width",w)
.attr("height",h)
.style("background-color","lavender")
.style('float','left')
//读取外部数据
d3.csv('20data.csv',function(error,data){
data.forEach(function(d){
dataset.push({key:d.date,value:+d.money})//value转换成数值型
xmark.push(d.date)
})
console.log(dataset)
console.log(xmark)
xScale=d3.scaleBand()
.domain(xmark)
.range([30,w-30])
.paddingInner(0.05)
yScale=d3.scaleLinear()
.domain([0,d3.max(dataset,function(d){return d.value})])
.range([h-30,30])
xAxis=d3.axisBottom()
.scale(xScale)
yAxis=d3.axisLeft()
.scale(yScale)
render(dataset)//要在内部渲染
})
//日期比例尺
var mydate=d3.scaleOrdinal()
.domain(d3.range(dataset.length))
.range(["Mon","Tue","Wed","Thr","Fri","Sat","Sun"])
//添加事件监听
//更新
d3.select('#auto')
.on('click',function(){
i=-1;
setInterval(function(){
i++;
dataset.shift()
xmark.shift()
dataset.push({key:mydate(i),value:Math.round(Math.random()*180)})
xmark.push(mydate(i))
render(dataset)
},1000)//间隔1000ms执行一个操作
})
function render(data){//封装函数
//更新比例尺输入、输出域
xScale.domain(xmark)
yScale.domain([0,d3.max(data,function(d){return d.value})])
xAxis.scale(xScale)
yAxis.scale(yScale)
var bar=svg.selectAll("rect")
.data(data)
//enter
bar.enter()
.append("rect")
.attr("x",function(d,i){return xScale(d.key)})
.attr("y",function(d){return yScale(d.value)})
.attr("width",xScale.bandwidth())
.attr("height",function(d,i){return h-30-yScale(d.value)})
.style("fill","blue")
//updata
bar.transition()
.attr("x",function(d,i){return xScale(d.key)})
.attr("y",function(d,i){return yScale(d.value)})
.attr("height",function(d){return h-30-yScale(d.value)})
.attr("width",xScale.bandwidth())
.style("fill","blue")
//exit
bar.exit()
.transition()
.duration(200)
.attr('x',w)
.remove()
myAxis(svg)
}
function myAxis(svg){
svg.select('#axisG')
.remove()
var axisG=svg.append('g')
.attr('id','axisG')
axisG.append('g')
.attr('transform','translate(0,170)')
.call(xAxis)
axisG.append('g')
.attr('transform','translate(30,0)')
.call(yAxis)
}
</script>
</body>
</html>