【问题标题】:d3 line graph does not present data correctly when called again再次调用时 d3 折线图无法正确显示数据
【发布时间】:2014-07-02 01:41:24
【问题描述】:

我正在尝试使用下面的 d3 折线图代码绘制手机上加速度计读数的 x、y、z 值。第一次测量非常适合绘图。随后的测量虽然会产生一个奇数图,其中每个值都是一条平线,然后像最后以非常高的频率压缩一样。但是,如果我重置应用程序并再次运行它,图表就很好了。当我导出数据并在电子表格中查看时,它似乎给出了有效的(即更改 x、y、z 和时间值)。我认为这可能是速度问题,并且已将测量时间减少到甚至 1000 毫秒,但问题仍然存在。创建第一个图形后,似乎没有重置变量。

我将加速度计数据以 json 格式存储在本地存储中,以测量时间为键。要获取图表,我使用密钥(存储在 div id 中以从本地存储中获取正确的 json 文件,然后将其转换为数组以供 d3 设置读取。

任何想法将不胜感激。

谢谢

function graph() {

    var key = $("#graph_info").text();

    var dataObject = window.localStorage.getItem(key);

    var data = JSON.parse(dataObject);


    data = $.map(data, function(value, index) {
    return [value];
});

    // set up a colour variable
    var color = d3.scale.category10();

    // map one colour each to x, y and z
    // keys grabs the key value or heading of each key value pair in the json
    // but not time
//    console.log(d3.keys(data[0]));
    color.domain(d3.keys(data[0]).filter(function(key) {
        return key !== "timestamp";
    }));

    // create a nested series for passing to the line generator
    // it's best understood by console logging the data
    var series = color.domain().map(function(name) {
        return {
            name: name,
            values: data.map(function(d) {
                return {
                    timestamp: d.timestamp,
                    score: +d[name]
                };
            })
        };
    });

    // Set the dimensions of the canvas / graph
    var margin = {
        top: 40,
        right: 20,
        bottom: 35,
        left: 30
    },
        width = 260 - margin.left - margin.right,
        height = 220 - margin.top - margin.bottom;

//        height = 120 - margin.top - margin.bottom;


    // 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
    // Note you plot the time / score pair from each key you created ealier 
    var valueline = d3.svg.line()
        .x(function(d) {
            return x(d.timestamp);
        })
        .y(function(d) {
            return y(d.score);
        });


    // Adds the svg canvas
    var svg = d3.select("#graph")
        .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 + ")");

    // Scale the range of the data
    x.domain(d3.extent(data, function(d) {
        return d.timestamp;
    }));

    // note the nested nature of this you need to dig an additional level
    y.domain([
        d3.min(series, function(c) {
            return d3.min(c.values, function(v) {
                return v.score;
            });
        }),
        d3.max(series, function(c) {
            return d3.max(c.values, function(v) {
                return v.score;
            });
        })
    ]);

    // create a variable called series and bind the date
    // for each series append a g element and class it as series for css styling
    var series = svg.selectAll(".series")
        .data(series)
        .enter().append("g")
        .attr("class", "series");

    // create the path for each series in the variable series i.e. x, y and z
    // pass each object called x, y nad z to the lne generator
    series.append("path")
        .attr("class", "line")
        .attr("d", function(d) {
 //           console.log(d); // to see how d3 iterates through series
            return valueline(d.values);
        })
        .style("stroke", function(d) {
            return color(d.name);
        });

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

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

    //top title message
    svg.append("text")
        .attr("x", (width / 2))             
        .attr("y", 0 - (margin.top / 2))
        .attr("text-anchor", "middle")  
        .style("font-size", "16px")  
        .text(key);

    //Lower X-Axis title
    svg.append("text")      // text label for the x axis
        .attr("x", width / 2 )
        .attr("y",  height + margin.bottom)
        .style("text-anchor", "middle")
        .text("Seconds from measurement");

    svg = "";
    key = "";
    dataObject = "";
    data = [];

};

function showCurrentGraph() {
    graph(); 


}    



// End graphing code

【问题讨论】:

  • 您的选择被命名为您的数据数组,此外,元素的属性仅在输入时设置。查看答案了解更多详情。

标签: json graph d3.js


【解决方案1】:

您正在使用与您的数据相同的名称来命名您的选择:

// Use another name for the selection
var series = svg.selectAll(".series")
    .data(series)
    .enter().append("g")
    .attr("class", "series");

此外,问题在于您仅在输入时将属性分配给元素,而不是更新它们。例如,仅使用系列组,您的代码应该看起来更像这样:

// Create the selection and bind the data
var series = svg.selectAll("g.series").data(data);

// Append elements on enter (make sure to add the class at this point)
series.enter().append("g").attr("class", "series");

// Update the attributes of the series (transform in this case)
series.attr('transform', function(d, i) { return 'translate(' + i + ', 0)'; });

// Remove the lines on exit.
series.exit().remove();

我强烈推荐阅读 Mike Bostock 的以下文章:How selections workNested SelectionsTowards Reusable charts。问候,

【讨论】:

  • 嗨,Pablo,非常感谢您提供的信息。我输入了上面的例子即:
  • 嗨,Pablo,非常感谢您提供的信息。您是否介意考虑一下我在进行此更改时遇到的挑战?我输入了上面的示例(来自第二个代码区域),但现在收到一条错误消息,提示“未捕获的 TypeError:无法读取未定义的属性 'length'” 当我使用时:var series = svg.selectAll("g.series") .data(series) ...我没有得到错误。我将尝试找出那里未定义数据的原因并阅读您发送的参考资料——非常感谢;)
  • 好的,我想我在这里犯了一个新手错误,因为添加 .data(data[0]) 会停止错误,但会提供一个空白图表。我猜这个数组有一个范围值?抱歉,如果这对每个人来说都很明显,我仍然习惯 d3。谢谢
  • 你能分享data变量的结构吗?我认为绑定不正确。
  • 我正在读取加速度计数据并将其“推送”到一个数组中,然后将该数组转换为带有时间戳的 json 作为本地存储的键。我在让控制台打印数组格式时遇到问题。但是 json 文件(减去时间戳看起来像: [{"x":0.4405331015586853,"y":-0.3256114423274994,"z":10.017339706420898,"timestamp":1404306774439}, ... ] json 文件转换回一个应该具有类似格式的数组(即 x、y、z、时间戳),但我是 Javascript 新手,正在摸索;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-09
  • 2023-03-24
  • 2019-03-02
  • 2021-11-22
  • 2022-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多