【问题标题】:New to d3, unable to show graph with jsond3 新手,无法使用 json 显示图形
【发布时间】:2015-02-12 11:01:14
【问题描述】:

我对 d3 非常非常陌生,但在获取带有 json 的折线图时遇到问题。

在我的 ReportBucketDAO.java 中,我使用我的数据库数据生成了 json。

while (rs.next()) 
{
     String currency = rs.getString("currency");

     Timestamp pointDateTimeTs = rs.getTimestamp("point_datetime");
     String pointDateTime = pointDateTimeTs.toString();
     pointDateTime = pointDateTime.substring(0, pointDateTime.indexOf('.'));
     double pointValue = rs.getDouble("sum(`point_value`)");
     org.json.JSONObject jobj = new org.json.JSONObject();
     jobj.put("currency", currency);
     jobj.put("pointDateTime", pointDateTime);
     jobj.put("pointValue", pointValue);
     jArray.add(jobj);
}

json字符串为:

[{"pointValue":274,"pointDateTime":"2015-01-20 00:00:00","currency":"GBP"}, {"pointValue":571,"pointDateTime":"2015-01-20 00:00:00","currency":"SGD"}, {"pointValue":561,"pointDateTime":"2015-01-20 00:00:00","currency":"USD"}]

我还有一个名为 getVolumeData.jsp 的 jsp,它允许我将上述 json 保存到“data.json”

<%@page import="java.util.ArrayList"%>
<%@page import="com.ach.model.ReportBucket"%>
<%@page import="com.ach.model.ReportBucketDAO"%>
<%@page import="java.io.*"%>
<%@page import="org.json.simple.*"%>
<%
    ReportBucketDAO rbDAO = new ReportBucketDAO();

    JSONArray rbjson = rbDAO.retrieveByReportTypeJson();
    System.out.println(rbjson);
    request.setAttribute("rbJsonString", rbjson);

    try {
        FileWriter jsonFileWriter = new FileWriter("data.json");
        jsonFileWriter.write(rbjson.toJSONString());
        jsonFileWriter.flush();
        jsonFileWriter.close();
        System.out.println("Done");
    } catch (IOException e) {
        e.printStackTrace();
    }
%>

我在 home.jsp 内容中调用 d3 内容

<!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta name="description" content="">
            <meta name="author" content="">
            <link rel="icon" href="../../favicon.ico">

            <title>Project</title>

            <link rel="shortcut icon" href="assets/img/tBank.ico">

            <!-- Bootstrap core CSS -->
            <link href="assets/css/bootstrap.min.css" rel="stylesheet">
            <script data-require="d3@3.5.3" data-semver="3.5.3" src="assets/js/d3.js"></script>

            <!-- Custom styles for this template -->
            <link href="assets/css/dashboard.css" rel="stylesheet">

            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
            <script type="text/javascript" src="assets/js/script.js"></script>
            <script>
                $(function() {
                    $("#header").load("header.jsp");
                    $("#sidebar").load("sidebar.html");
                    //$("#d3content").load("getVolumeData.jsp");
                });
            </script> 
        </head>

    <body>
    <div id="header"></div>
    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar" id="sidebar">
          <!--Sidebar here-->
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <!--                    <img id="loading" src="assets/img/ajax_load.gif" alt="loading" />-->
          <div id="pageContent">
            <!-- this is where our AJAX-ed content goes -->
            <h1 class="page-header">My Dashboard</h1>
          </div>
          <div id="d3content">
            <script type="text/javascript">
                $("#d3content").load(function(event){
                    // Set the dimensions of the canvas / graph
            var margin = {
              top: 30,
              right: 20,
              bottom: 70,
              left: 50
            },
              width = 600 - margin.left - margin.right,
              height = 300 - margin.top - margin.bottom;

             // Parse the date / time
            var parseDate = d3.time.format("%Y-%m-%d %X").parse;

             // Set the ranges
            var x = d3.time.scale().range([0, width]);
            var y = d3.scale.linear().range([height, 0]);

             // Define the axes
            var xAxis = d3.svg.axis().scale(x)
              .orient("bottom").ticks(5);

            var yAxis = d3.svg.axis().scale(y)
              .orient("left").ticks(5);

             // Define the line
            var priceline = d3.svg.line()
              .x(function(d) {
                return x(d.pointDateTime);
              })
              .y(function(d) {
                return y(d.pointTime);
              });

             // Adds the svg canvas
            var svg = d3.select("#d3content")
              .append("svg")
              .attr("width", width + margin.left + margin.right)
              .attr("height", height + margin.top + margin.bottom)
              .append("g")
              .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");

             // Get the data
            d3.json("data.json", function(error, data) {
              data.forEach(function(d) {
                d.symbol = d.currency;
                d.pointDateTime = parseDate(d.pointDateTime);
                d.pointTime = +d.pointValue;
              });
              console.log(data);
              // Scale the range of the data
              x.domain(d3.extent(data, function(d) {
                return d.pointDateTime;
              }));
              y.domain([0, d3.max(data, function(d) {
                return d.pointTime;
              })]);

              // Nest the entries by symbol
              var dataNest = d3.nest()
                .key(function(d) {
                  return d.symbol;
                })
                .entries(data);

              console.log(dataNest);

              var color = d3.scale.category10(); // set the colour scale

              legendSpace = width / dataNest.length; // spacing for the legend

              // Loop through each symbol / key
              dataNest.forEach(function(d, i) {
                console.log(d);
                svg.append("path")
                  .attr("class", "line")
                  .style("stroke", function() { // Add the colours dynamically
                    return d.color = color(d.key);
                  })
                  .attr("id", 'tag' + d.key.replace(/\s+/g, '')) // assign ID
                .attr("d", priceline(d.values));

                // Add the Legend
                svg.append("text")
                  .attr("x", (legendSpace / 2) + i * legendSpace) // space legend
                .attr("y", height + (margin.bottom / 2) + 5)
                  .attr("class", "legend") // style the legend
                .style("fill", function() { // Add the colours dynamically
                  return d.color = color(d.key);
                })
                  .on("click", function() {
                    // Determine if current line is visible 
                    var active = d.active ? false : true,
                      newOpacity = active ? 0 : 1;
                    // Hide or show the elements based on the ID
                    d3.select("#tag" + d.key.replace(/\s+/g, ''))
                      .transition().duration(100)
                      .style("opacity", newOpacity);
                    // Update whether or not the elements are active
                    d.active = active;
                  })
                  .text(d.key);

              });

              // Add the X Axis
              svg.append("g")
                .attr("class", "x axis")
                .attr("transform", "translate(0," + height + ")")
                .call(xAxis);

              // Add the Y Axis
              svg.append("g")
                .attr("class", "y axis")
                .call(yAxis);

            });
                });
          </script>
          </div>
        </div>
      </div>
    </div>
    <!-- Bootstrap core JavaScript
        ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script data-require="bootstrap@3.3.1" data-semver="3.3.1" src="assets/js/bootstrap.min.js"></script>
    <!--<script src="assets/js/docs.min.js"></script>-->

  </body>
</html>

我希望将 d3 加载到 d3content 中,但它不显示/显示任何内容,有什么帮助吗?

【问题讨论】:

  • 不管您可能遇到什么其他问题,您肯定会想要d3.select("#d3content") 而不是d3.select("body")
  • 你在哪里加载 d3?

标签: java jquery json netbeans d3.js


【解决方案1】:

问题如下:

1.) 你没有加载d3.js

2.) 您的变量未正确映射。在这个区块中:

data.forEach(function(d) {
    d.currency = +d.currency; // this is a string do not use +
    d.pointDateTime = parseDate(d.pointDateTime);
    d.pointTime = +d.pointTime; // your json is pointValue, not pointTime
});

3.) 您的日期解析函数错误。应该是:

var parseDate = d3.time.format("%Y-%m-%d %X").parse;

清理它,生成这个example

【讨论】:

  • 感谢您的帮助,但我在 data.json 中遇到了一些问题,因为我使用的是 Netbeans Java EE 6 Web。所以基本上我还有一个名为 getVolumeData.jsp 的 jsp,我希望将我的 json 保存为 data.json (我已经更新了上面的代码,你可以检查......)我很抱歉我把它遗漏了,但真的感谢您的帮助!
  • 即使我的data.json和你的一样,我的图表似乎仍然没有出现......
  • 所以你的json在一个名为rbJson的java变量中;你在哪里把它交给javascript?另外,您是否更改了代码以加载d3.js最重要的是,您检查过 javascript 控制台是否有错误?那些错误是什么?
  • 我根据你的 Plunker 更改了我的代码,并使用了你在 data.json 中的相同数据,但它仍然没有显示任何图形迹象。
  • 最重要的是,您检查过 javascript 控制台是否有错误?这些错误是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 2022-01-01
  • 1970-01-01
  • 2012-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多