d3.js 封装一个方法更新柱状图,运用数据模板
生活随笔
收集整理的這篇文章主要介紹了
d3.js 封装一个方法更新柱状图,运用数据模板
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<script>var width = 400;var height = 400;//創建畫布var svg = d3.select('body').append('svg').attr('width',width).attr('height',height)var padding = {top:20,left:20,right:20,bottom:20}var rectstep = 35; //矩形的寬帶偏白var rectwidth = 30;//矩形的寬var dataset = [216,86,158,76,203]// 根據數據填充矩形var rect = svg.selectAll('rect').data(dataset).enter().append('rect').attr('fill','steelblue').attr('x',function(d,i){return padding.left + i * rectstep;}).attr('y',function(d,i){return height - padding.bottom - d;}).attr('width',rectwidth).attr('height',function(d,i){return d;}) // 根據數據填充文本內容 var text = svg.selectAll('text').data(dataset).enter().append('text').attr('fill','white').attr('x',function(d,i){return padding.left + i * rectstep;}).attr('y',function(d,i){return height - padding.bottom - d;}).attr('text-anchor','middle') .attr('font-size','14px').attr('dx',rectwidth/2)
.attr('dy','1em').text(function(d,i){return d;})function draw(){// 獲取矩形的update部分var updateRect = svg.selectAll('rect').data(dataset);// 獲取矩形的enter部分var enterRect = updateRect.enter();// 獲取矩形的exit部分var exitRect = updateRect.exit();// update部分處理辦法
updateRect.attr("fill","steelblue").attr("x",function(d,i){return padding.left + i * rectstep;}).attr("y",function(d,i){return height - padding.bottom - d;}).attr("width",rectwidth).attr("height",function(d,i){return d;})//enter部分處理辦法
enterRect.append("rect").attr("fill","steelblue").attr("x",function(d,i){return padding.left + i * rectstep;}).attr("y",function(d,i){return height - padding.bottom - d;}).attr("width",rectwidth).attr("height",function(d,i){return d;}) // exit部分處理辦法
exitRect.remove(); // 獲取文本的update部分var updateText = svg.selectAll('text').data(dataset)// 獲取文本的enter部分var enterText = updateText.enter();// 獲取文本的exit部分var exitText = updateText.exit();// 文本update部分的處理辦法
updateText.attr("fill","white") .attr("font-size","14px").attr("text-anchor","middle").attr("x",function(d,i){return padding.left + i * rectstep;}).attr("y",function(d,i){return height- padding.bottom - d;}).attr("dx",rectwidth/2)
.attr("dy","1em").text(function(d,i){return d;});// 文本enter部分處理辦法
enterText.append("text").attr("fill","white").attr("font-size","14px").attr("text-anchor","middle").attr("x",function(d,i){return padding.left + i * rectstep;}).attr("y",function(d,i){return height- padding.bottom - d;}).attr("dx",rectwidth/2)
.attr("dy","1em").text(function(d,i){return d;}); // 文本exit部分的處理辦法
exitText.remove();} </script><button onclick="mysort()">排序</button><button onclick="myadd()">增加數據</button><script>function mysort() {dataset.sort(d3.ascending);draw();}function myadd() {dataset.push( Math.floor(Math.random()*100));draw();}</script>
轉載于:https://www.cnblogs.com/webmc/p/11076230.html
總結
以上是生活随笔為你收集整理的d3.js 封装一个方法更新柱状图,运用数据模板的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python目录及文件操作
- 下一篇: Selenium3+python自动化0