我一直在教自己d3,似乎无法弄清楚我遇到的这个问题.我正在通过HTML 元素动态地为d3.max()方法提供一个数字数组(我尝试用parseInt()/ 解析它们parseFloat()以及不解析它们)<select>.我正在使用控制台检查值,因为我的可视化变得歪斜.但是,有时它会返回最大值,有时它不会.
var localityElectricityConsumption = localities[localityName].totalElectricityConsumption;
maxConsumption = d3.max(localityElectricityConsumption);
r = d3.scale.linear().domain([0, maxConsumption]).range([120, 0]);
console.log("array being fed to d3.max: " + localityElectricityConsumption);
console.log("what d3.max() is returning: " + d3.max(localityElectricityConsumption));
console.log("what parseInt(d3.max()) is returning: " + d3.max(localityElectricityConsumption));
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看实时可视化并检查控制台.尝试使用最顶层的图表从北美地区切换到墨西哥地区.d3.max()返回北美的最大值,但不返回墨西哥,因此不会为墨西哥正确绘制数据.我正式难过.任何帮助,将不胜感激.
编辑:
以下是用于创建的代码localities[localityName].totalElectricityConsumption:
d3.csv("data/" + dataset, function (data) {
for (var i = 0; i < data.length; i++) {
var record = data[i];
if (dataset === "total_electricity_consumption.csv") {
currentDataset = listOfDatasets[0].name;
record.totalElectricityConsumption = [];
// loop through all years, from 1980 to 2012
for (var year = 1980; year <= 2012; year++) {
var value = record[year];
// deal with missing data points
if (value === '--') {
value = 0;
}
else if (value === 'NA') {
value = 0;
}
else if (value === '(s)') {
value = 0;
}
else if (value === 'W') {
value = 0;
}
// add record of current total electricity consumption
record.totalElectricityConsumption.push(value);
}
}
// create a list of country names
localities[record.Locality] = record;
listOfLocalities.push(record.Locality);
}
}
Run Code Online (Sandbox Code Playgroud)
对不起,格式化并不完美,因为我不得不采取一些措施来使代码更易于Stack Overflow.
正如预期的那样,d3.max()确实返回了最大值...但是,它返回字符串中的最大值,而不是数字.
解释是,默认情况下,d3.csv()将所有值加载为字符串,即使它们是数字.因此,当你这样做时:
var value = record[year];
Run Code Online (Sandbox Code Playgroud)
value是一个字符串,而不是一个数字.在JavaScript中,字符串数组的最大值与数组数组的最大值不同.例如,使用数字:
var myArray = [1, 65, 9, 32, 42];
console.log(d3.max(myArray));Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v4.min.js"></script>Run Code Online (Sandbox Code Playgroud)
这是预期的价值.但看看如果我们使用字符串会发生什么:
var myArray = ["1", "65", "9", "32", "42"];
console.log(d3.max(myArray));Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v4.min.js"></script>Run Code Online (Sandbox Code Playgroud)
解决方案:将您的值更改为数字:
var value = +record[year];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1062 次 |
| 最近记录: |