【问题标题】:plotting json data in phant using d3 js使用 d3 js 在 phant 中绘制 json 数据
【发布时间】:2017-01-23 06:37:16
【问题描述】:

我正在尝试使用 d3.js 来可视化存储在 sparkfun cloud(物联网云)中的数据。 There is example using google chart for visualizing sparkfun cloud,使用以下脚本:

<!DOCTYPE html>
<html>
  <head>
    <!-- EXTERNAL LIBS-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://www.google.com/jsapi"></script>

    <!-- EXAMPLE SCRIPT -->
    <script>

      // onload callback
      function drawChart() {

        var public_key = 'dZ4EVmE8yGCRGx5XRX1W';

        // JSONP request
        var jsonData = $.ajax({
          url: 'https://data.sparkfun.com/output/' + public_key + '.json',
          data: {page: 1},
          dataType: 'jsonp',
        }).done(function (results) {

          var data = new google.visualization.DataTable();

          data.addColumn('datetime', 'Time');
          data.addColumn('number', 'Temp');
          data.addColumn('number', 'Wind Speed MPH');

          $.each(results, function (i, row) {
            data.addRow([
              (new Date(row.timestamp)),
              parseFloat(row.tempf),
              parseFloat(row.windspeedmph)
            ]);
          });

          var chart = new google.visualization.LineChart($('#chart').get(0));

          chart.draw(data, {
            title: 'Wimp Weather Station'
          });

        });

      }

      // load chart lib
      google.load('visualization', '1', {
        packages: ['corechart']
      });

      // call drawChart once google charts is loaded
      google.setOnLoadCallback(drawChart);

    </script>

  </head>
  <body>
    <div id="chart" style="width: 100%;"></div>
  </body>
</html>

我希望使用 d3.js 来绘制数据,而不是使用谷歌图表,因为它提供了更大的灵活性(我很惊讶需要花费多少精力来使用谷歌图表重新调整图表的大小)。为此可能需要使用d3.js json提取器从网站获取数据。我根据问题1,2进行了以下尝试:

var data1;
var url = "https://data.sparkfun.com/output/dZ4EVmE8yGCRGx5XRX1W.json"

d3.json(url, function (json) {
         if (error) return console.warn(error);
     //data1 = json;
     data1=json;
     consol.log(data1)
             //code here
                     })

它没有工作。我可能缺少一些关键信息,因为我是 d3.js 和 java 的新手。请给我一个方向,以便我可以遵循。谢谢!

【问题讨论】:

  • 你的回调函数中error在哪里定义?我会删除它并重试:-)

标签: javascript json d3.js


【解决方案1】:

由于您试图捕获error,因此您必须将错误作为匿名函数的第一个参数传递:

d3.json(url, function (error, json) {
    //first argument -----^
    if (error) return console.warn(error);
    data1=json;
    consol.log(data1)
    //code here
 })

注意这一点:在d3.json中,“error”是第一个参数,而不是第二个。

一个更简单的选择是简单地删除“错误”:

d3.json(url, function (json) {
    data1=json;
    consol.log(data1)
    //code here
 })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 2015-01-01
    相关资源
    最近更新 更多