gpt4 book ai didi

javascript - d3 数组输入折线图示例

转载 作者:行者123 更新时间:2023-11-28 15:46:52 25 4
gpt4 key购买 nike

我对 d3 非常陌生,为了学习,我正在尝试操纵 d3.js line example ,代码如下。我正在尝试修改它以使用我手头已有的模型数据。该数据作为 json 对象传递下来。问题是我不知道如何操作数据以满足 d3 的期望。大多数 d3 示例都使用键值数组。我想使用键数组+值数组。例如,我的数据是按照以下示例构建的:

// my data. A name property, with array values and a value property with array values.
// data is the json object returned from the server
var tl = new Object;
tl.date = data[0].fields.date;
tl.close = data[0].fields.close;
console.log(tl);

这是直观的结构(是的,现在是时间格式):

My Data

现在这与 data.tsv 不同调用会在下面的代码中生成键值对。

key-value data

目标是按原样使用我的数据,而无需迭代数组来对其进行预处理。

问题:

1) d3 是否有任何内置函数可以处理这种情况?例如,如果键值在Python中是绝对必要的,我们可以使用zip函数快速生成键值列表。

2) 我可以按原样使用我的数据吗,或者它必须转换成键值对吗?

下面是行示例代码。

// javascript/d3 (LINE EXAMPLE)
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 640 - margin.left - margin.right,
height = 480 - margin.top - margin.bottom;

var parseDate = d3.time.format("%d-%b-%y").parse;

var x = d3.time.scale()
.range([0, width]);

var y = d3.scale.linear()
.range([height, 0]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

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

var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });

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 + ")");

d3.tsv("/data.tsv", function(error, data) {
data.forEach(function(d) {

d.date = parseDate(d.date);
d.close = +d.close;
});

x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));

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

svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");

svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});

最佳答案

查看d3's array functions , zip 就在其中。

这是使用您的数据的原始要点的注释版本:http://bl.ocks.org/patrickberkeley/9162034

其核心是:

// 1) Zip the close value with their corresponding date/time
// Results in an array of arrays:
//
// [[582.13, "02:30:00"], [583.98, "02:45:00"], ...]
//
data = d3.zip(data.close, data.date).map(function(d) {
// 2) Format each close and date/time value so d3 understands what each represents.
close = +d[0];

// If your data source can't be changed at all, I'd rename `date` to `time` here.
date = parseTime(d[1]);

// 3) Return an object for each close and date/time pair.
return {close: close, date: date};
});

关于javascript - d3 数组输入折线图示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21957231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com