【问题标题】:Cannot read my Json file to draw a line chart using D3.js code无法读取我的 Json 文件以使用 D3.js 代码绘制折线图
【发布时间】:2014-05-08 19:40:45
【问题描述】:

此代码由js编写,使用D3 Libarary绘制折线图。我遇到一个错误,控制台显示与 d3.v3.min.js:1 相关的 (TypeError: e is undefined)) 并且当我单击 firefox 的调试器点击时,它会显示这行数据

!function(){function n(n,t){return t>n?-1:n>t?1:n>=t?0:0/0}function t(n){return null! =n&&!isNaN(n)}函数e(n){return{left:function(t,e,r,u){for(arguments.lengthr;){var i=r+u>>>1;n(t[i],e)

这是我的 Json 文件

    {
"Id": 2,
"Name": "ukraine",
"Occurrences": [
    {
        "OccurrenceDate": "Jan 2000",
        "OccurrenceFrequency": 136
    },
    {
        "OccurrenceDate": "Feb 2000",
        "OccurrenceFrequency": 2
    },
    {
        "OccurrenceDate": "Mar 2000",
        "OccurrenceFrequency": 89
    }
   ]}

这是我的代码,我的代码是根据日期制作折线图

<script src="http://d3js.org/d3.v3.min.js"></script>``
<script>

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

    var parse = d3.time.format("%b %Y").parse;

    // Scales and axes. Note the inverted domain for the y-scale: bigger is up!

    var x = d3.time.scale().range([0, width]),
    y = d3.scale.linear().range([height, 0]),
    xAxis = d3.svg.axis().scale(x).tickSize(-height).tickSubdivide(true),
    yAxis = d3.svg.axis().scale(y).ticks(4).orient("right");

    // An area generator, for the light fill.

    var area = d3.svg.area()
   .interpolate("monotone")
   .x(function (d) { return x(d.OccurrenceDate); })
   .y0(height)
   .y1(function (d) { return y(d.OccurrenceFrequency); });

    // A line generator, for the dark stroke.

    var line = d3.svg.line()
   .interpolate("monotone")
   .x(function (d) { return x(d.OccurrenceDate); })
   .y(function (d) { return y(d.OccurrenceFrequency); });

    d3.json("readme.json", type, function (error, data) {

        // Filter to one Name; ukraine.

        var values = data.filter(function (d) {
            return d.Name == "ukraine";
        });

        // Compute the minimum and maximum date, and the maximum OccurrenceFrequency.

        x.domain([values[0].OccurrenceDate, values[values.length - 1].OccurrenceDate]);
        y.domain([0, d3.max(values, function (d) { return d.OccurrenceFrequency; })]).nice();

        // Add an SVG element with the desired dimensions and margin.

        var svg = d3.select("body").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 + ")")
       .on("click", click);

        // Add the clip path.

        svg.append("clipPath")
       .attr("id", "clip")
       .append("rect")
       .attr("width", width)
       .attr("height", height);

        // Add the area path.

        svg.append("path")
       .attr("class", "area")
       .attr("clip-path", "url(#clip)")
       .attr("d", area(values));

        // 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")
       .attr("transform", "translate(" + width + ",0)")
       .call(yAxis);

        // Add the line path.

        svg.append("path")
       .attr("class", "line")
       .attr("clip-path", "url(#clip)")
       .attr("d", line(values));

        // Add a small label for the name.

        svg.append("text")
       .attr("x", width - 6)
       .attr("y", height - 6)
       .style("text-anchor", "end")
       .text(values[0].Name);

        // On click, update the x-axis.

        function click() {
            var n = values.length - 1,
             i = Math.floor(Math.random() * n / 2),
             j = i + Math.floor(Math.random() * n / 2) + 1;
            x.domain([values[i].OccurrenceDate, values[j].OccurrenceDate]);
            var t = svg.transition().duration(750);
            t.select(".x.axis").call(xAxis);
            t.select(".area").attr("d", area(values));
            t.select(".line").attr("d", line(values));
        }
    });

    // Parse dates and numbers. We assume values are sorted by date.

    function type(d) {
        d.OccurrenceDate = parse(d.OccurrenceDate);
        d.OccurrenceFrequency = +d.OccurrenceFrequency;
        return d;
    }

</script>

【问题讨论】:

  • 为什么将 JSON 包装在 (...) 中;而不是只保留在 { ... } 中?
  • 消息“e未定义”出现在哪一行?我在您的代码中找不到名为“e”的变量。
  • 在 conslo 中没有说具体的行 ((TypeError: e is undefined))
  • 您的调试器抱怨“第 1 行”很长,因为文件已被缩小。尝试使用常规的“d3js.org/d3.v3.js”而不缩小。也许这会为我们指出一个(可读的)d3 函数以便更好地理解。
  • Webserver: d3.json 会做一个 GET 请求。您的文件是否在(本地)网络服务器上,或者只是从您的 windows/mac/linux 的文件夹中打开?最后一个无法处理网络服务器请求,因此不会提前加载文件。

标签: jquery css json svg linechart


【解决方案1】:

要使用 d3.json(),您需要设置一个网络服务器。这很简单。 从 Windows 资源管理器打开文件将显示静态内容,但无法处理通过“HTTP GET”加载更多文件。我猜是因为没有加载 json 文件,所以 d3.json 中的字符串不仅是空的,而且是未定义的。

  • 下载捆绑在一个简单安装包中的XAMPP - apache webserver, database etc
  • 将 HTML 和 JSON 文件放在“htdocs”文件夹中。在您的安装路径中查找名为“htdocs”的文件夹(例如 C:\xamppfiles\htdocs)。
  • 通过xampp控制中心启动webserver。
  • 在您的网络浏览器中导航到 localhost/nameOfTheHtmlFile.html
  • 发布回复,您看到的内容以及可能显示的错误。

【讨论】:

  • 出了点问题,我不能下载xampp。你能分享我一个下载链接吗?
  • 这里是XAMPP for Windows v1.8.3 (PHP 5.5.11)的直接下载链接
  • 这行不通。我使用另一个 wbserver 连接它。我仍然面临同样的问题!!!!
  • 使用“乌克兰”数据的工作图查看新答案
【解决方案2】:

如果它看起来像这样,请继续阅读 4 个提示。

我做了一些更新:

JSON 需要是一个数组,所以如果可能的话,用 [ ] 将它包围(我认为,d3 提供了一些对象到数组的转换器)

[{
"Id": 2,
"Name": "ukraine",
"Occurrences": [... ]
}] // brackets are important

d3.json(url, callbackFunction) 这只需要两个参数,而不是三个。

d3.json( "soD3Question.json", function ( data ) { ... });

解析时间格式 您不能将此函数添加到 d3.json。您可以遍历数组并自行更改值。

var parse = d3.time.format( "%b %Y" ).parse;
var parseAllDates = function (  ) {
    for ( var i = 0; i < data[0].Occurrences.length; i++ ) {
        data[0].Occurrences[i].OccurrenceDate = parse( data[0].Occurrences[i].OccurrenceDate );
    }
}

d3.json( "soD3Question.json", function ( jsonData ) {
        data = jsonData;
        parseAllDates( ); // call date parser
        ...

SVG 颜色我只能猜测,因为没有提供样式表,并且图像包含 3 个黑色重叠路径,例如颜色

path.domain{ fill: lightgrey; }
path.line{ fill: white;}
path.area{ fill: grey; }

---------所以这里有完整的代码(不要忘记json文件中的括号)-----------

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
    <title></title>
    <style>
        path.domain {fill: lightgrey;}
        path.line {fill: white;}
        path.area {fill: grey;}
    </style>
</head>
<body>
<script>
    var margin = { top: 80, right: 80, bottom: 80, left: 80 },
            width = 960 - margin.left - margin.right,
            height = 500 - margin.top - margin.bottom;
    var data;
    var parse = d3.time.format( "%b %Y" ).parse;
    var parseAllDates = function () {
        for ( var i = 0; i < data[0].Occurrences.length; i++ ) {
            data[0].Occurrences[i].OccurrenceDate = parse( data[0].Occurrences[i].OccurrenceDate );
        }
    }
    // Scales and axes. Note the inverted domain for the y-scale: bigger is up!

    var x = d3.time.scale().range( [0, width] ),
            y = d3.scale.linear().range( [height, 0] ),
            xAxis = d3.svg.axis().scale( x ).tickSize( -height ).tickSubdivide( true ),
            yAxis = d3.svg.axis().scale( y ).ticks( 4 ).orient( "right" );

    // An area generator, for the light fill.

    var area = d3.svg.area()
            .interpolate( "monotone" )
            .x( function ( d ) {
                return x( d.OccurrenceDate );
            } )
            .y0( height )
            .y1( function ( d ) {
                return y( d.OccurrenceFrequency );
            } );

    // A line generator, for the dark stroke.

    var line = d3.svg.line()
            .interpolate( "monotone" )
            .x( function ( d ) {
                return x( d.OccurrenceDate );
            } )
            .y( function ( d ) {
                return y( d.OccurrenceFrequency );
            } );


    //    d3.json( "soD3Question.json", type, function ( error, data ) {
    d3.json( "soD3Question.json", function ( jsonData ) {
        data = jsonData;
        parseAllDates();
        // Filter to one Name; ukraine.

        var values = data.filter( function ( d ) {
            return d.Name == "ukraine";
        } );


        // Compute the minimum and maximum date, and the maximum OccurrenceFrequency.
        values = values[0].Occurrences;
        x.domain( [values[0].OccurrenceDate, values[values.length - 1].OccurrenceDate ] );
        y.domain( [0, d3.max( values, function ( d ) {
            return d.OccurrenceFrequency;
        } )] ).nice();

        // Add an SVG element with the desired dimensions and margin.

        var svg = d3.select( "body" ).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 + ")" )
                .on( "click", click );

        // Add the clip path.

        svg.append( "clipPath" )
                .attr( "id", "clip" )
                .append( "rect" )
                .attr( "width", width )
                .attr( "height", height );

        // 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" )
                .attr( "transform", "translate(" + width + ",0)" )
                .call( yAxis );

        // Add the line path.

        svg.append( "path" )
                .attr( "class", "line" )
                .attr( "clip-path", "url(#clip)" )
                .attr( "d", line( values ) );

        // Add the area path.

        svg.append( "path" )
                .attr( "class", "area" )
//                .attr( "clip-path", "url(#clip)" ) // needs to be defined
                .attr( "d", area( values ) );

        // Add a small label for the name.
        svg.append( "text" )
                .attr( "x", width - 6 )
                .attr( "y", height - 6 )
                .style( "text-anchor", "end" )
                .text( values[0].Name );

        // On click, update the x-axis.

        function click() {
            var n = values.length - 1,
                    i = Math.floor( Math.random() * n / 2 ),
                    j = i + Math.floor( Math.random() * n / 2 ) + 1;
            x.domain( [values[i].OccurrenceDate, values[j].OccurrenceDate] );
            var t = svg.transition().duration( 750 );
            t.select( ".x.axis" ).call( xAxis );
            t.select( ".area" ).attr( "d", area( values ) );
            t.select( ".line" ).attr( "d", line( values ) );
        }
    } );
</script>

</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多