How to read in data into d3.js from multiple javascript arrays? And dynamically updating chart without refreshing the page

不问归期 提交于 2019-12-08 13:54:17

问题


Currently I have two arrays, one is a list of numbers titled nums, and the ms is a list of strings titled places.

Ex.

nums=[1,2,3,4,5]

places = ["house","gym", "work", "school", "park"] 

both arrays are the same length.

I want to make a bar chart with these arrays that looks similar to http://bl.ocks.org/mbostock/3885304, but the data is coming from these arrays rather than a tsv file.

In Bostock's code the data is read in from a tsv file, the code is below.

d3.tsv("data.tsv", type, function(error, data) {
  x.domain(data.map(function(d) { return d.letter; }));
  y.domain([0, d3.max(data, function(d) { return d.frequency; })]);

Additionally, I am receiving updates from a server and the data on certain bars will be updating while other bars are constant. Rather than refreshing the page I want to update the bars which change. For this type of project should I try to use something like react, or any other recommendations. Help here would be greatly appreciated. Thanks!!


回答1:


If you want to use Mike Bostock's code then you could create an array called data, with a num property and a place property:

var data=[]; 
for(var i=0; i<nums.length; i++){
var obj = {num: nums[i], place: places[i]};
data.push(obj);
}

Then you can get rid of the d3.tsv call. Obviously you'll also need to replace Mike's references to d.letter and d.frequency with d.place and d.num.

In your javascript code, listen for whatever event signals that the data has been updated and then call your chart plotting method when this occurs.



来源:https://stackoverflow.com/questions/24231357/how-to-read-in-data-into-d3-js-from-multiple-javascript-arrays-and-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!