javascript - 获取对象的特定属性以进行绘图
问题描述
我正在尝试使用 D3 来绘制与时间相关的数据。我导入的文件有多个通道。我想在图表上显示每个数据通道。
我正在尝试格式化 var "dataset",以便 d3 可以将其识别为要绘制的数字列表。
抓取数据:
var dataset = d3.tsv("/Data/"+`${fridge}`+getInstrumentURL(instrumentArray[1]))
.then( data =>
{
data.forEach( d =>
{
d['Date Time'] = new Date(d['Date Time']);
d.Tpt1 = +d.Tpt1;
d.Tpt2 = +d.Tpt2;
d.Tstill = +d.Tstill;
d.Tdblstill = +d.Tdblstill;
d.Tcp = +d.Tcp;
d.Tmc = +d.Tmc;
d.Tsamp = +d.Tsamp;
});
console.log(data);
}); // converts strings to numbers. Console log confirms my data transfer.
绘图:
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 + ")");
svg.append("path") //lines connecting data points
.datum(dataset) //here i want to use channel Tpt1, Tpt2, etc.
.attr("class", "line")
.attr("d", line);
svg.selectAll(".dot") //data POINTS
.data(dataset)
.enter().append("circle") // Uses the enter().append() method
.attr("class", "dot")
.attr("cx", function(d, i) { return xScale(i) })
.attr("cy", function(d) { return yScale(d.y) })
.attr("r", 5)
就像“数据集”:页面加载,图中没有数据。
作为dataset[]['Tpt1']
:页面加载不正确
作为dataset['Tpt1']
:未定义的错误。我知道为什么这是错误的(索引),但是如何传递整个数组以便绘制每个 Tpt1 值?
我正在尝试使用此 Bl.ocks 示例,但使用 TSV:https ://bl.ocks.org/gordlea/27370d1eea8464b04538e6d8ced39e89
解决方案
我不完全理解这个问题,但看看这一行:
var dataset = d3.tsv('/yourpath...')
你不了解异步tsv()
函数是如何工作的,因为它总是会返回 undefined 给dataset
变量。数据只有在Promise
设置 byd3.tsv()
被解析并执行回调函数时才可用then()
。
您应该将构建可视化的代码放在一个函数中,以便在then()
获取数据时可以在函数的回调中调用它,如下所示。
// Define you code that builds the vizualization within a function that
// accepts your dataset as an argument. This function can then be called
// whenever you have access to your data.
function buildMyViz(data) {
var svg = d3.select('graph')
... etc
}
var dataset; // Define dataset outside of your request for data
d3.tsv('/yourpath...').then(function(returnedData) {
// When the data is returned (asynchronously), you can assign it to dataset
dataset = returnedData;
// Now you have the data you can trigger the code that builds the d3 viz
buildMyViz(dataset);
});
推荐阅读
- swift - Swift:将泛型变量约束为类或协议
- linux - 我需要在 docker 中创建多主机网络吗?
- javascript - 如何使用 GraphQL 查询返回目录中的文件列表?
- reactjs - 使用 Flexbox 和 React Native 的容器外部文本
- laravel - 为什么当我选择所有数据时显示但当我使用查找或即使我使用 dd 检查时数据不显示时
- ios - 为什么 OAuth 重定向在 iOS 13 中不起作用,但在 iOS 12 中起作用?
- android - 如何根据 Fragment 区分 SearchView 提交的操作?
- c++ - 此 ECS 实施在多大程度上遵循了这些原则
- powershell - 当要求移动文件时,Powershell 无法识别路径
- python - 没有名为“tensorflow”的模块 jupyter notebook