D3.JS图表没有显示

时间:2017-08-23 21:11:20

标签: javascript json d3.js charts data-visualization

我的D3.js图表​​存在问题。所以我试图从我项目中的本地文件解析JSON数据,并用它创建一个D3图表。我本地文件的URL具有正确的JSON数组。但是,出于某种原因,我的图表没有显示。我的图表基于这个:https://codepen.io/mrev/pen/waKvbw

提前致谢!

使用Javascript:

import sys

from twisted.internet import reactor
from twisted.web.resource import Resource
from autobahn.twisted.resource import WebSocketResource

from ws_transport import WsProtocol, WsProtocolFactory
from web_transport import HttpResource, LoginResource, RefreshResource, HttpFactory


if __name__ == '__main__':
    factory = WsProtocolFactory()
    factory.protocol = WsProtocol
    ws_resource = WebSocketResource(factory)

    root = Resource()
    root.putChild("", HttpResource())
    root.putChild("login", LoginResource())
    root.putChild("refresh", RefreshResource())
    root.putChild(b"ws", ws_resource)

    site = HttpFactory(root)

    reactor.listenTCP(8000, site)

    reactor.run()

HTML:

function createSeries() {

    var margin = { top: 5, right: 5, bottom: 30, left: 40 },
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

    // scale to ordinal because x axis is not numerical
    var x = d3.scale.ordinal().rangeRoundBands([0, width], .1);

    //scale to numerical value by height
    var y = d3.scale.linear().range([height, 0]);

    var chart = d3.select("#chart")
                  .append("svg")  //append svg element inside #chart
                  .attr("width", width + (2 * margin.left) + margin.right)    //set width
                  .attr("height", height + margin.top + margin.bottom);  //set height
    var xAxis = d3.svg.axis()
                  .scale(x)
                  .orient("bottom");  //orient bottom because x-axis will appear below the bars

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

    d3.json("../Rma/GetNmcPareto", function (error, data) {
        alert(error);
        x.domain(data.map(function (d) { return d.Wuc }));
        y.domain([0, d3.max(data, function (d) { return d.Hours})]);

        var bar = chart.selectAll("g")
                          .data(data)
                        .enter()
                          .append("g")
                          .attr("transform", function (d, i) {
                              return "translate(" + x(d.Wuc) + ", 0)";
                          });

        bar.append("rect")
            .attr("y", function (d) {
                return y(d.Hours);
            })
            .attr("x", function (d, i) {
                return x.rangeBand() + (margin.left / 2);
            })
            .attr("height", function (d) {
                return height - y(d.Hours);
            })
            .attr("width", x.rangeBand());  //set width base on range on ordinal data

        bar.append("text")
            .attr("x", x.rangeBand() + margin.left)
            .attr("y", function (d) { return y(d.Hours) - 10; })
            .attr("dy", ".75em")
            .text(function (d) { return d.Hours; });

        chart.append("g")
              .attr("class", "x axis")
              .attr("transform", "translate(" + margin.left + "," + height + ")")
              .call(xAxis);

        chart.append("g")
              .attr("class", "y axis")
              .attr("transform", "translate(" + margin.left + ",0)")
              .call(yAxis)
              .append("text")
              .attr("transform", "rotate(-90)")
              .attr("y", 6)
              .attr("dy", ".71em")
              .style("text-anchor", "end")
              .text("Hours");
    });

    function type(d) {
        d.Wuc = +d.Wuc; // coerce to number
        return d;
    }

};

JSON数据:

   @{
    ViewBag.Title = "Nmc Pareto";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Nmc Pareto</h2>



<div class="row">
    <div class="col-lg-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <i class="fa fa-area-chart fa-fw"></i>NMC Pareto
            </div>
            <!-- /.panel-heading -->
            <div class="panel-body">
                <div id="divtitle" class="text-center"></div>
                <table>
                    <tbody>
                        <tr>
                            <td id="pnlFilters">
                                <div class="collapse width">
                                    <form id="fmSearch" role="form" data-toggle="validator">
                                        <div>
                                            <div>

                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </td>
                            <td id="btnOpenFilters">
                                <a href="#" data-toggle="collapse" data-target="#pnlFilters>div">
                                    <div>
                                        <span class="filterArrowTop glyphicon glyphicon-chevron-right"></span>
                                        <span class="sidePanelText openFiltersText">Filters</span>
                                        <span class="filterArrowBottom glyphicon glyphicon-chevron-right"></span>
                                    </div>
                                </a>
                            </td>
                            <td style="width: 100%;" rowspan="2">
                                <svg id="chart">

                                </svg>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <!-- /.panel-body -->
        </div>
    </div>
</div>


@section styles {
    <link rel="stylesheet" type="text/css" href="~/Content/themes/base/jquery.ui.all.css" />
    <link rel="stylesheet" type="text/css" href="~/Content/Views/Rma/NmcPareto.css" />
}

@section scripts{
    <script type="text/javascript" src="~/Scripts/Views/Rma/NmcPareto.js"></script>
    <script type="text/javascript" src="~/Scripts/d3.min.js"></script>
}

1 个答案:

答案 0 :(得分:0)

这可能会有所帮助,它有一个鼠标悬停工具提示,填充颜色会发生变化。

&#13;
&#13;
<!DOCTYPE html>
<meta charset="utf-8">

<body>
  <style>
    .bars:hover {
      fill: blue;
    }
    
    .legend:hover {
      fill: blue;
    }
    /* tooltip for bar chart */
    
    div.tooltip {
      position: absolute;
      text-align: center;
      width: 50px;
      height: 60px;
      padding: 2px;
      font: 12px sans-serif;
      background: lightsteelblue;
      border: 0px;
      border-radius: 8px;
      pointer-events: none;
    }
  </style>
  <div id="bar_chart">
  </div>
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <script>
    //  d3.json("data.json", function(error, data) {
    //  if (error) throw error;
    // var parseTime = d3.timeParse("%M:%S");
    // var timeformat = d3.timeFormat("%M:%S")

    data = [{
        "Wuc": "23A",
        "Nomenclature": "Engine, Basic (F117-PW)",
        "Hours": 155899.90
      },
      {
        "Wuc": "23V",
        "Nomenclature": "F‌​an Thrust Reverser",
        "Hours": 56576
      }
    ]

    data.forEach(function(d) {
      // d.atime = parseTime(d.atime);
      d.Hours = +d.Hours;
    });
    var margin = {
        top: 70,
        right: 50,
        bottom: 100,
        left: 80
      },
      width = 600 - margin.left - margin.right,
      height = 600 - margin.top - margin.bottom;
    //Define the div for the tooltip
    var div = d3.select("body").append("div")
      .attr("class", "tooltip")
      .style("opacity", 0);
    var x = d3.scaleBand()
      .domain(data.map(function(d) {
        return d.Wuc
      }))
      .range([0, width])
      .padding([0.8]); //sets decimal of the space between bar centres
    var y = d3.scaleLinear()
      .domain([0, d3.max(data, function(d) {
        return d.Hours
      })])
      .range([height, 0]);
    var svg = d3.select("#bar_chart")
      .data(data)
      .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 + ")");
    // Add the X Axis
    svg.append("g")
      .attr("class", "axis")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));
    // text label for the x axis
    svg.append("text")
      .attr("x", width / 2)
      .attr("y", margin.top + height)
      .style("text-anchor", "middle")
      .style("font-weight", "bold")
      .text("x-Axis Title");
    // Add the Y Axis
    svg.append("g")
      .attr("class", "axis")
      .call(d3.axisLeft(y)
        .ticks(5));
    // text label for the y axis
    svg.append("text")
      .attr("class", "blah")
      .attr("transform", "rotate(-90)")
      .attr("x", 0 - height / 2)
      .attr("y", -50)
      .style("text-anchor", "middle")
      .style("font-weight", "bold")
      .text("y-Axis Title");
    // graph main title
    svg.append("text")
      .attr("x", width / 2)
      .attr("y", -20)
      .style("text-anchor", "middle")
      .style("font-weight", "bold")
      .style("font-size", "20px")
      .text("Main Title");
    //********* Bar Chart ****************
    var rects = svg.selectAll('rect')
      .data(data)
      .enter();
    rects.append('rect')
      .on("mouseover", function(d, i, node) { //this is repeated should be in a function
        div.transition()
          .duration(200)
          .style("opacity", .85);
        div.html("<strong> Name:</strong> " + d.Wuc + "</br><strong> Value:</strong> " + d.Hours)
          .style("left", (d3.event.pageX + 5) + "px")
          .style("top", (d3.event.pageY - 28) + "px");
        d3.select(this)
          .style("fill", "blue");
      })
      .on("mouseout", function(d) {
        div.transition()
          .duration(500)
          .style("opacity", 0);
        d3.select(this)
          .style("fill", "lightblue");
      })
      .attr("class", "bars") //should fill blue on mouseover, not working???
      .attr('x', function(d, i) {
        return x(d.Wuc);
      })
      .attr('y', function(d, i) {
        return y(d.Hours);
      })
      .attr('height', function(d, i) {
        return height - y(d.Hours)
      })
      .attr('width', x.bandwidth())
      .attr("transform", "translate(0,0)")
      .style('fill', 'lightblue')
      .style('stroke', 'lightgray');
    // }); //closes function d3.json("data.json", function(error, data) {.....
  </script>
&#13;
&#13;
&#13;