0

Here is my code:

<script>

        var response = null;
        ////get pie data from postgredql
        $(document).ready(function () {

            $.ajax({
                url: "/piedata",
                type: "get",
                dataType: 'json',
                async: false,
                contentType: "application/json",

                success: function (msg) {

                   // alert("msg");
                    //alert(JSON.stringify(msg));
                    msg1 = JSON.stringify(msg);
                    response = JSON.parse(msg1);
                    //alert(JSON.stringify(response));
                    //alert(response);
                }

            });
        });
        var canvas = d3.select('#piec')
                        .append('svg')
                        .attr({ 'width': 1000, 'height': 600, 'radius' : 1000 });

        //var data = [{ "label": "Maximo", "value": 10},
        //            { "label": "ASD", "value": 40},
        //            { "label": "Iportman", "value": 5},
        //            { "label": "Sales", "value": 10},
        //            { "label": "Finance", "value": 10},
        //            { "label": "HR", "value": 10 }];

        var data = JSON.stringify(response);

              //alert(data);
        //alert(response);
              alert(JSON.stringify(response));


              var colors = ['Tomato', 'DodgerBlue'];


        var colorscale = d3.scale.linear().domain([0, data.length]).range(colors);

        var arc = d3.svg.arc()
                        .innerRadius(0)
                        .outerRadius(250);

        var arcOver = d3.svg.arc()
                        .innerRadius(0)
                        .outerRadius(200 + 10);

        var pie = d3.layout.pie()
                        .value(function (d) { return d.value; });


        var renderarcs = canvas.append('g')
                        .attr('transform', 'translate(600,300)')
                        .selectAll('.arc')
                        .data(pie(data))
                        .enter()
                        .append('g')
                        .attr('class', "arc");

        renderarcs.append('path')
                .attr('d', arc)
                .attr('fill', function (d, i) { return colorscale(i); })
                .on("mouseover", function (d) {
                    d3.select(this).transition()
                       .duration(1000)
                       .attr("d", arcOver);
                })
                .on("mouseout", function (d) {
                    d3.select(this).transition()
                       .duration(1000)
                       .attr("d", arc);
                });

        renderarcs.append('text')
                .attr('transform', function (d) {
                    var c = arc.centroid(d);
                    console.log(c);
                    return "translate(" + c[0] + "," + c[1] + ")";
                })
            .attr("text-anchor", "middle")
            .text(function (d, i) { return data[i].State; });

    </script>

and here it is app.js code:

app.get('/piedata', function (req, res) {

    var sql = require("mssql");

    // config for your database
    var config = {
        user: 'sa',
        password: 'password',
        server: 'localhost',
        database: 'datas',
        port: '5124'
    };

    // connect to your database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records
        request.query('select State,sales from Orders$', function (err, result) {

            if (err) console.log(err)

            // send records as a response
            res.send(result);
            sql.close();

        });
    });
});

Please let me know how to append that data in pie chart to draw pie chart and using nodejs, sql server,jquery and i need to draw pie chart from sql server data and i am using two parameters which was i have to draw pie chart and i am getting response from server but not able to append that data in chart.

  • can you post your server response with question? – Dipak Mar 22 '18 at 09:04
  • it was huge of amount of data anyway {"recordsets":[[{"State":"Kentucky","sales":261.96},{"State":"Kentucky","sales":731.9399999999999},{"State":"California","sales":14.62},{"State":"Florida","sales":957.5775},{"State":"Florida","sales":22.368000000000002},{"State":"California","sales":48.86},{"State":"California","sales":7.28},{"State":"California","sales":907.152},{"State":"California","sales":18.504},{"State":"California","sales":114.9},{"State":"California","sales":1706.1840000000002},{"State":"California","sales":911.424},{"State":"North Carolina","sales":15.552000000000003} –  Mar 22 '18 at 09:12
  • it is enough prasanth – Dipak Mar 22 '18 at 09:20
  • but data is not appending to pie chart –  Mar 22 '18 at 09:30
  • showing this error now Unexpected value translate(NaN,NaN) parsing transform attribute. –  Mar 22 '18 at 09:38
  • at least give me few minutes to work on your code – Dipak Mar 22 '18 at 09:42
  • can you send me piechart link which you are trying to integrate – Dipak Mar 22 '18 at 09:43
  • http://bl.ocks.org/kiranml1/6872886 –  Mar 22 '18 at 09:47
  • I post an answer let me know whether it will resolve your issue or not? – Dipak Mar 22 '18 at 10:10
  • let me know prasanth reason why an answer has downvote? – Dipak Mar 22 '18 at 10:15
  • It was working fine for static data and i was looking for dynamic data.... which is comes from sql server and i am not sure about that downvote –  Mar 22 '18 at 10:22
  • prasanth I deleted my answer I thought you downvote. – Dipak Mar 22 '18 at 10:57
  • I also did same thing – Dipak Mar 22 '18 at 10:57
  • I have updated an answer with dynamic data comes from API as well as static data answer . Looking forward for your response. – Dipak Mar 22 '18 at 11:23

2 Answers2

-1

https://codepen.io/anon/pen/PRmdBZ

Your issue was in the below piece of code.

 var pie = d3.layout.pie()
                    .value(function (d) { return d.value; });

It had to be

 var pie = d3.layout.pie()
                    .value(function (d) { return d.sales; });
user1496463
  • 410
  • 3
  • 14
  • Got this error, Error: o.map is not a function After including this code –  Mar 22 '18 at 09:58
-1

Dynamic data

Following code with dynamic data fetch from api. I have used temporary dummy API to give you an answer and get clear idea.

<!DOCTYPE html>
<html>

  <head>
    <meta content="utf-8" http-equiv="encoding">
    <title>Dsnap - Charts</title>
  </head>

  <body>
    <div id="wrapper">
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <script>
      $(document).ready(function() {
        function loadD3Canvas(data) {
          var canvas = d3.select('#wrapper')
            .append('svg')
            .attr({
              'width': 650,
              'height': 500
            });

          var colors = ['red', 'blue'];
          var colorscale = d3.scale.linear().domain([0, data.length]).range(colors);

          var arc = d3.svg.arc()
            .innerRadius(0)
            .outerRadius(100);

          var arcOver = d3.svg.arc()
            .innerRadius(0)
            .outerRadius(150 + 10);

          var pie = d3.layout.pie()
            .value(function(d) {
              return d.high;
            });


          var renderarcs = canvas.append('g')
            .attr('transform', 'translate(440,200)')
            .selectAll('.arc')
            .data(pie(data))
            .enter()
            .append('g')
            .attr('class', "arc");

          renderarcs.append('path')
            .attr('d', arc)
            .attr('fill', function(d, i) {
              return colorscale(i);
            })
            .on("mouseover", function(d) {
              d3.select(this).transition()
                .duration(1000)
                .attr("d", arcOver);
            })
            .on("mouseout", function(d) {
              d3.select(this).transition()
                .duration(1000)
                .attr("d", arc);
            });

          renderarcs.append('text')
            .attr('transform', function(d) {
              var c = arc.centroid(d);
              return "translate(" + c[0] + "," + c[1] + ")";
            })
            .text(function(d) {
              return d.data.high;
            });
        }
        $.ajax({
          url: " https://api.iextrading.com/1.0/stock/aapl/chart",
          type: "get",
          dataType: 'json',
          async: false,
          contentType: "application/json",

          success: function(msg) {
            msg1 = JSON.stringify(msg);
            response = JSON.parse(msg1);
            loadD3Canvas(response);
          }
        });
      });

    </script>
  </body>

</html>

Static Data format described in your code

This is working snippet on my local machine please review it and let me know if any issue arises.

<!DOCTYPE html>
<html>

<head>
  <meta content="utf-8" http-equiv="encoding">
  <title>Dsnap - Charts</title>
</head>

<body>
  <div id="wrapper">
  </div>
  <script src="https://d3js.org/d3.v3.min.js"></script>
  <script>
    var canvas = d3.select('#wrapper')
      .append('svg')
      .attr({
        'width': 650,
        'height': 500
      });


    var data = {
      "recordsets": [
        { "State": "Kentucky", "sales": 261.96 },
        { "State": "Kentucky", "sales": 731.9399999999999 },
        { "State": "California", "sales": 14.62 },
        { "State": "Florida", "sales": 957.5775 },
        { "State": "Florida", "sales": 22.368000000000002 },
        { "State": "California", "sales": 48.86 },
        { "State": "California", "sales": 7.28 },
        { "State": "California", "sales": 907.152 },
        { "State": "California", "sales": 18.504 },
        { "State": "California", "sales": 114.9 },
        { "State": "California", "sales": 1706.1840000000002 },
        { "State": "California", "sales": 911.424 },
        { "State": "North Carolina", "sales": 15.552000000000003 }
      ]
    };
    var colors = ['red', 'blue'];
    var colorscale = d3.scale.linear().domain([0, data.recordsets.length]).range(colors);

    var arc = d3.svg.arc()
      .innerRadius(0)
      .outerRadius(100);

    var arcOver = d3.svg.arc()
      .innerRadius(0)
      .outerRadius(150 + 10);

    var pie = d3.layout.pie()
      .value(function (d) {
        return d.sales;
      });


    var renderarcs = canvas.append('g')
      .attr('transform', 'translate(440,200)')
      .selectAll('.arc')
      .data(pie(data.recordsets))
      .enter()
      .append('g')
      .attr('class', "arc");

    renderarcs.append('path')
      .attr('d', arc)
      .attr('fill', function (d, i) {
        return colorscale(i);
      })
      .on("mouseover", function (d) {
        d3.select(this).transition()
          .duration(1000)
          .attr("d", arcOver);
      })
      .on("mouseout", function (d) {
        d3.select(this).transition()
          .duration(1000)
          .attr("d", arc);
      });

    renderarcs.append('text')
      .attr('transform', function (d) {
        var c = arc.centroid(d);
        return "translate(" + c[0] + "," + c[1] + ")";
      })
      .text(function (d) {    
        return d.value;
      });
  </script>
</body>

</html>
Dipak
  • 2,248
  • 4
  • 22
  • 55