javascript - 无法从数据集制作饼图

标签 javascript d3.js

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Testing Pie Chart</title>
         <script src="d3.v3.min.js" charset="utf-8"></script>
         <style type="text/css">
         #chart {  
            margin-top: 100px;                                              
            position: absolute;  
            margin-right: 50px;
            margin-left: 50px;                                           
          }                                                                 
          .tooltip {                                                        
            background: #eee;                                               
            box-shadow: 0 0 5px #999999;                                    
            color: #900C3F;                                                    
            display: inline-block;                                                  
            font-size: 12px;                                                
            left: 600px;                                                    
            padding: 10px;                                                  
            position: absolute;                                             
            text-align: center;                                             
            top: 95px;                                                      
            width: 150px;                                                    
            z-index: 10;  
            opacity: 1;                                                 
        }                                                                 
        rect {
           stroke-width: 2;
        }
        path {
          stroke: #ffffff;
          stroke-width: 0.5;
      }
      div.tooltip {
      position: absolute;
      z-index: 999;
      padding: 10px;
      background: #f4f4f4;
      border: 0px;
      border-radius: 3px;
      pointer-events: none;
      font-size: 11px;
      color: #000;
      line-height: 16px;
      border: 1px solid #d4d4d4;
      }

      .legend{
        margin-left: 300px;
      }
         </style>
      </head>
      <body>
        <div id="chart"></div>
        <div id="toolTip" class="tooltip" style="opacity: 0;"></div>
        <script type="text/javascript">

    var div = d3.select("#toolTip");

           var data = [ ["IP", "count"]
          ["192.168.12.1", "20"], 
          ["76.09.45.34", "40"], 
          ["34.91.23.76", "80"],
          ["192.168.19.32", "16"], 
          ["192.168.10.89", "50"], 
          ["192.178.34.07", "18"],
          ["192.168.12.98", "30"]];

    var width = 300,
      height = 300;
    var margin = {top: 15, right: 15, bottom: 20, left: 40},
      radius = Math.min(width, height) / 2 - 10;
    var legendRectSize = 18,
        legendSpacing = 4;
          

        var color = d3.scale.category20b();

        var arc = d3.svg.arc()
            .outerRadius(radius);
          
          var arcOver = d3.svg.arc()
                .outerRadius(radius + 10);

        var pie = d3.layout.pie()
            .sort(null)
            .value(function(d) { return d.data.count; });

          var labelArc = d3.svg.arc()
            .outerRadius(radius - 40)
            .innerRadius(radius - 40);
          
        var svg = d3.select("#chart").append("svg")
            .datum(data)
            .attr("width", width)
            .attr("height", height)
            .append("g")
            .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

        var arcs = svg.selectAll(".arc")
            .data(pie)
            .enter().append("g")
            .attr("class", "arc");
          
         var arcs2 = svg.selectAll(".arc2")
            .data(pie)
            .enter().append("g")
            .attr("class", "arc2");

          
        arcs.append("path")
            .attr("fill", function(d, i) { return color(i); })
            .on("mouseover", function(d) {
            var htmlMsg="";
              div.transition()    
                    .style("opacity",0.9);
                  var total = d3.sum(data.map(function(d) {                   
                      return d.count;                                           
                  })); 
            var percent = Math.round(1000 * d.data.count / total) / 10;     
                div.html(
                 "IP :"+ d.data.IP +""+"<br/>"+
                 "Count : " +  d.data.count +"<br/>" + 
                 "Percent: " + percent + '%'+ htmlMsg)
                .style("left",  (d3.event.pageX) + "px")
                  .style("top",  (d3.event.pageY) + "px");  

              svg.selectAll("path").sort(function (a, b) { 
                  if (a != d) return -1;               
                else return 1;                             
              });
          
            var endAngle = d.endAngle + 0.1;
            var startAngle = d.startAngle - 0.1;
            var arcOver = d3.svg.arc()
                  .outerRadius(radius + 10).endAngle(endAngle).startAngle(startAngle);
                      d3.select(this)
                        .attr("stroke","white")
                        .transition()
                        .ease("bounce")
                        .duration(1000)
                        .attr("d", arcOver)             
                        .attr("stroke-width",6);
                  })

            .on("mouseout", function(d) {
                  div.transition()        
                    .duration(500)      
                    .style("opacity", 0); 
                    d3.select(this).transition()            
                       .attr("d", arc)
                       .attr("stroke","none");
                })
              .transition()
              .ease("bounce")
              .duration(2000)
              .attrTween("d", tweenPie);

        function tweenPie(b) {
          b.innerRadius = 0;
          var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
          return function(t) { return arc(i(t)); };
        }

            var k=0;
        arcs2.append("text")
        .transition()
            .ease("elastic")
          .duration(2000)
          .delay(function (d, i) {
            return i * 250;
          })
              .attr("x","6")
              .attr("dy", ".35em")
              .text(function(d) { if(d.data.count >0){ k = k+1; return d.data.count;} })
              .attr("transform", function(d) { if (k >1){return "translate(" + labelArc.centroid(d) + ") rotate(" + angle(d) + ")";} else{return "rotate(-360)";} })
              .attr("font-size", "10px");
          

        function type(d) {
          d.count = +d.count;
          return d;
        }
        function angle(d) {
              var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
              return a > 90 ? a - 180 : a;
        }

     var legend = d3.select("#chart")
        .append("svg")
        .attr("class", "legend")
        .attr("width", radius+50)
        .attr("height", radius * 2)
        .selectAll("g")
        .data(color.domain())
        .enter()
        .append("g")
        .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

     legend.append('rect')
        .attr('width', legendRectSize)
        .attr('height', legendRectSize)                                   
       .style('fill', color)
       .style('stroke', color);
      
      legend.append('text')
        .attr('x', legendRectSize + legendSpacing)
        .attr('y', legendRectSize - legendSpacing)
        .data(data)
        .text(function(d,i) { return d.IP; });
        
        
        </script>
      </body>
     </html>

我正在尝试使用提供的数据集制作饼图,但遇到错误。如何定义参数d以从变量“data”及其后续值“IP”和“count”中获取数据?我不知道我的代码中犯了什么错误。我应该对当前代码进行哪些更改才能获得具有当前数据格式的饼图?请帮我。我被困住了。条件是我不应该在此代码中使用任何类型的 .csv 或 .tsv 文件进行导入。谢谢你的帮助。

最佳答案

  • 一个问题是您的数据数组...您需要删除其中的第一项[此外,您在该项目后面缺少一个“,”。但该项目本身并不是必需的,因为它是一个数组]。

  • 第二个是饼图函数内的 d.data.count ...您需要将其引用为 d[1],因为您需要在图表中的数据数组中绘制第二项。

下面的工作代码:

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Testing Pie Chart</title>
         <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
         <style type="text/css">
         #chart {  
            margin-top: 100px;                                              
            position: absolute;  
            margin-right: 50px;
            margin-left: 50px;                                           
          }                                                                 
          .tooltip {                                                        
            background: #eee;                                               
            box-shadow: 0 0 5px #999999;                                    
            color: #900C3F;                                                    
            display: inline-block;                                                  
            font-size: 12px;                                                
            left: 600px;                                                    
            padding: 10px;                                                  
            position: absolute;                                             
            text-align: center;                                             
            top: 95px;                                                      
            width: 150px;                                                    
            z-index: 10;  
            opacity: 1;                                                 
        }                                                                 
        rect {
           stroke-width: 2;
        }
        path {
          stroke: #ffffff;
          stroke-width: 0.5;
      }
      div.tooltip {
      position: absolute;
      z-index: 999;
      padding: 10px;
      background: #f4f4f4;
      border: 0px;
      border-radius: 3px;
      pointer-events: none;
      font-size: 11px;
      color: #000;
      line-height: 16px;
      border: 1px solid #d4d4d4;
      }

      .legend{
        margin-left: 300px;
      }
         </style>
      </head>
      <body>
        <div id="chart"></div>
        <div id="toolTip" class="tooltip" style="opacity: 0;"></div>
        <script type="text/javascript">

    var div = d3.select("#toolTip");

           var data = [ 
          ["192.168.12.1", "20"], 
          ["76.09.45.34", "40"], 
          ["34.91.23.76", "80"],
          ["192.168.19.32", "16"], 
          ["192.168.10.89", "50"], 
          ["192.178.34.07", "18"],
          ["192.168.12.98", "30"]];

    var width = 300,
      height = 300;
    var margin = {top: 15, right: 15, bottom: 20, left: 40},
      radius = Math.min(width, height) / 2 - 10;
    var legendRectSize = 18,
        legendSpacing = 4;
          

        var color = d3.scale.category20b();

        var arc = d3.svg.arc()
            .outerRadius(radius);
          
          var arcOver = d3.svg.arc()
                .outerRadius(radius + 10);

        var pie = d3.layout.pie()
            .sort(null)
            .value(function(d) { return d[1]; });

          var labelArc = d3.svg.arc()
            .outerRadius(radius - 40)
            .innerRadius(radius - 40);
          
        var svg = d3.select("#chart").append("svg")
            .datum(data)
            .attr("width", width)
            .attr("height", height)
            .append("g")
            .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

        var arcs = svg.selectAll(".arc")
            .data(pie)
            .enter().append("g")
            .attr("class", "arc");
          
         var arcs2 = svg.selectAll(".arc2")
            .data(pie)
            .enter().append("g")
            .attr("class", "arc2");

          
        arcs.append("path")
            .attr("fill", function(d, i) { return color(i); })
            .on("mouseover", function(d) {
            var htmlMsg="";
              div.transition()    
                    .style("opacity",0.9);
                  var total = d3.sum(data.map(function(d) {                   
                      return d.count;                                           
                  })); 
            var percent = Math.round(1000 * d.data.count / total) / 10;     
                div.html(
                 "IP :"+ d.data.IP +""+"<br/>"+
                 "Count : " +  d.data.count +"<br/>" + 
                 "Percent: " + percent + '%'+ htmlMsg)
                .style("left",  (d3.event.pageX) + "px")
                  .style("top",  (d3.event.pageY) + "px");  

              svg.selectAll("path").sort(function (a, b) { 
                  if (a != d) return -1;               
                else return 1;                             
              });
          
            var endAngle = d.endAngle + 0.1;
            var startAngle = d.startAngle - 0.1;
            var arcOver = d3.svg.arc()
                  .outerRadius(radius + 10).endAngle(endAngle).startAngle(startAngle);
                      d3.select(this)
                        .attr("stroke","white")
                        .transition()
                        .ease("bounce")
                        .duration(1000)
                        .attr("d", arcOver)             
                        .attr("stroke-width",6);
                  })

            .on("mouseout", function(d) {
                  div.transition()        
                    .duration(500)      
                    .style("opacity", 0); 
                    d3.select(this).transition()            
                       .attr("d", arc)
                       .attr("stroke","none");
                })
              .transition()
              .ease("bounce")
              .duration(2000)
              .attrTween("d", tweenPie);

        function tweenPie(b) {
          b.innerRadius = 0;
          var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
          return function(t) { return arc(i(t)); };
        }

            var k=0;
        arcs2.append("text")
        .transition()
            .ease("elastic")
          .duration(2000)
          .delay(function (d, i) {
            return i * 250;
          })
              .attr("x","6")
              .attr("dy", ".35em")
              .text(function(d) { if(d.data.count >0){ k = k+1; return d.data.count;} })
              .attr("transform", function(d) { if (k >1){return "translate(" + labelArc.centroid(d) + ") rotate(" + angle(d) + ")";} else{return "rotate(-360)";} })
              .attr("font-size", "10px");
          

        function type(d) {
          d.count = +d.count;
          return d;
        }
        function angle(d) {
              var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
              return a > 90 ? a - 180 : a;
        }

     var legend = d3.select("#chart")
        .append("svg")
        .attr("class", "legend")
        .attr("width", radius+50)
        .attr("height", radius * 2)
        .selectAll("g")
        .data(color.domain())
        .enter()
        .append("g")
        .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

     legend.append('rect')
        .attr('width', legendRectSize)
        .attr('height', legendRectSize)                                   
       .style('fill', color)
       .style('stroke', color);
      
      legend.append('text')
        .attr('x', legendRectSize + legendSpacing)
        .attr('y', legendRectSize - legendSpacing)
        .data(data)
        .text(function(d,i) { return d.IP; });
        
        
        </script>
      </body>
     </html>

关于javascript - 无法从数据集制作饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959809/

相关文章:

javascript - 如何在D3中渲染对象数据?

javascript - 当我使用 D3 将鼠标悬停在第二个 SVG 的元素上时如何更改 SVG 中元素的属性

javascript - 为什么redux-thunks需要绑定(bind)dispatch?

Javascript 函数用于返回数组中长度超过定义数量的字符串

javascript - amCharts 无法显示数据?

javascript - 在 javascript 代码中包含 .json 数据 (d3.js)

javascript - dc.js:具有多个 CSV 的 ReduceSum

javascript - CSS - 浏览器如何知道在实现固定表头表时如何使两个表的列保持同步?

javascript - 如何在元素不超出父边界的情况下过渡高度?

javascript - 将日期格式更改为字符串 d3 js