dongli8862 2014-05-14 16:26
浏览 55

如何将动态数据提取到nvd3图表

I am trying to trying to draw Pie chart using nvd3 JavaScript library. It worked fine when tested with hard coded data. But what I want is to be able to fetch dynamic data from the server via php and Ajax. This has not been possible. Can someone kindly point me in the right direction? Thanks

jquery:

function chartdata() {
$.post('chartData.php', {
        id : $("#id").val(),
        theDate : $(".selectedDate").text()
    }, function(data) {
        var testdata = JSON.stringify(data);
        alert(testdata);
        console.log(testdata)

    }, 'json');

};

nvd3:

        nv.addGraph(function() {
            var width = 250, height = 250;
            var chart = nv.models.pieChart().x(function(d) {
                if (d.Code === "1") {
                    d.Code = "Good"
                } else if (d.Code === "2") {
                    d.Code = "Error"
                    }
                return d.Code;
            }).y(function(d) {
                return d.ReasonCount;
            }).width(width).height(height).showLabels(false).labelThreshold(.05)//Configure the minimum slice size for labels to show up
            .labelType("percent")//Configure what type of data to show in the label. Can be "key", "value" or "percent"
            .donut(true)//Turn on Donut mode. Makes pie chart look tasty!
            .donutRatio(0.45)//Configure how big you want the donut hole size to be.
            ;
            d3.select(".test2").datum(chartdata()).transition().duration(1200).attr('width', width).attr('height', height).call(chart);
            chart.dispatch.on('stateChange', function(e) {
                nv.log('New State:', JSON.stringify(e));
            });
            return chart;
        });

Sample JSON:

 [{"Code":"1","ReasonCount":"8"},{"Code":"2","ReasonCount":"1"}, ]
  • 写回答

1条回答 默认 最新

  • duanfuchi7236 2014-08-01 18:11
    关注

    I think I've managed to do what you want to with a bar chart. It may be a bit late for you but after you've gotten your JSON object variable from the server, the trick is to insert it into the correct location in the NVD3 script. If you are pulling data from a CSV file and plotting that data it looks like this:

    function bar() {
      $(document).ready(function(){
        d3.csv("http://localhost/ERC/database/data.csv",function(err,data){             //reads the csv file for data.
    
          var dataToPlot = Object.keys(data[0]).filter(function(k){return k!="date"})       //gets the values as an object
            .map(function(k){
              return {"key":k,"values":data.map(function(d){                                //specifies the key/value pair
               return {
                 "x":d.date,        //specifies x-axis values to use
                 "y":+d[k]          //parses the y axis into a number
               }
              })
              };
            });
        //execute bar chart code
        });
    });
    

    I used alert(JSON.stringify(JSON_object,null,4)); to see where my JSON object needed to be inserted into the code. Essentially what I did was delete the lines which call the csv file and then insert my JSON object (I passed it as "obj") in place of the original "data" object. You also need to make sure to modify the key value name. The modified code below works:

    function bar(obj) {
    
      $(document).ready(function(){
    
          var dataToPlot = Object.keys(obj[0]).filter(function(k){return k!="PID"})         //gets the values as an object
            .map(function(k){
              return {"key":k,"values":obj.map(function(d){                                 //specifies the key/value pair
               return {
                 "x":d.PID,                                                                 //specifies x-axis values to use
                 "y":+d[k]                                                          //parses the y axis into a number
               }
              })
              };
            });
        })
    }
    

    Hope this helps. I'm relatively new to programming and it took me a while to figure this out.

    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条