Pie Chart main source: ··· Home

Notes:

  • Added the animation (transition) by changing a random slice data by a random integer between range

Data: data.json

Code:

  • pie.ejs

    <%  demo = {category: "d3js", key: "pie", files: files}; %>
    
    <%- partial("../mixins/_demo_title", demo) %>
    
    <form><button id="change-data" class="btn btn-success" type="button">Change</button></form>
    
    <div id="chart" class="<%= demo.key %>-chart"></div>
    
    <script type="text/javascript" src="/vendors/bower/d3/d3.min.js"></script>
    <script type="text/javascript" src="/js/d3js/<%= demo.key %>.js"></script>
    
    <%- partial("../mixins/_notes", demo) %>
    <%- partial("../mixins/_sources_data", demo) %>
    <%- partial("../mixins/_code", demo) %>
  • pie.js

    $(document).ready(function() {
    
      const width = $("#chart").innerWidth()
      const height = 300
      const outerRadius = 100
      const color = d3.scale.category20()
      let arc = {}
    
      const stashArcs = ((d) => d.data.ea0 = _.cloneDeep(d))
    
      const arcTween = ((ar) => {
    
        const i = d3.interpolate(ar.data.ea0, ar)
    
        ar.data.ea0 = i(0)
        return ((t) => arc(i(t)))
    
      })
    
      const textTransform = (function(d) {
    
        d.outerRadius = outerRadius
        d.innerRadius = outerRadius / 2
        return `translate(${arc.centroid(d)})`
    
      })
    
      return d3.json("/data/d3js/pie/data.json", function(error, data) {
    
        const pie = d3.layout.pie().sort(null).value(((d) => d.val))
    
        arc = d3.svg.arc().outerRadius(outerRadius)
    
        const svg = d3.select("#chart").append("svg:svg").attr({width, height})
          .append("g").attr("transform", `translate(${width / 2},${height / 2})`)
    
        const slices = svg.selectAll(".slice").data(pie(data)).enter().append("g").attr("class", "slice")
    
        const path = slices.append("path").attr({fill(d, i) {
    
          return color(i)
    
        }, d: arc}).each(stashArcs)
    
        const labels = slices.filter((d) => d.endAngle - d.startAngle > .2)
          .append("text").attr({dy: ".35em", "text-anchor": "middle"})
          .attr("transform", textTransform).style({fill: "White", font: "bold 12px Arial"})
          .text((d) => d.data.val)
    
        slices.append("title").text((d) => d.data.label)
    
        return d3.select("#change-data").on("click", function() {
    
          const index = Math.floor(Math.random() * 5)
    
          data[index].val = Math.floor(Math.random() * 44) + 2
    
          path.data(pie(data)).transition().duration(1000).attrTween("d", arcTween)
          return labels.data(pie(data)).transition().duration(1000)
            .attr("transform", textTransform).each("start", function(d) {
    
              return d3.select(this).text(d.data.val)
    
            })
    
        })
    
      })
    
    })
    

Home