D3.js: draw simple line graph starting from data arrays

五迷三道 提交于 2021-02-07 10:30:20

问题


I have two arrays, one containing the data which should go into the X axis, the other the data which should become the Y entries.

How can I tell d3.js to take the data from those arrays and use it as data for its graph and then draw it?


回答1:


Can you use anything on top of D3? If so, check out http://c3js.org. C3 is built on top of D3, and it makes creating simple charts much easier.




回答2:


I needed to solve a similar problem. I've assembled the code I used and put it into a fiddle. However, I'm not a d3 expert and so while I can say this works, it might not be the best method. Furthermore, since I built this, I've found things like C3 and Dimple, as mentioned by John Grese in another answer, and those libraries could prove more useful for you.

Here's the fiddle:

http://jsfiddle.net/cf7a4afv/

It takes two arrays of data:

var x_data = [1,2,3,4,5,5.5,7,8,9,12]
var y_data = [1,5,4,6,4,3,5,6,7,8]

This data can build a simple line graph where the points (1,1), (2,5), (3,4) etc are plotted as (x,y) coords and joined by a line. I've thrown in a few edgecases, like x=5.5 and a jump from x=9 to x=12 to show that this method is quite flexible.

Then there are two functions that can turn each data point into a pixel on screen. These are based on the height and width of the graph:

var x = d3.scale.linear().domain([0, d3.max(x_data)]).range([0, w])
var y = d3.scale.linear().domain([0, d3.max(y_data)]).range([h, 0])

Then this gets turned into a line function. The key thing here is that the y function returns data from the y_data array; this is how we can use two arrays to create one graph.

var line = d3.svg.line()
    .x(function(d, i) {
        return x(d)
    })
    .y(function(d, i) {
        return y(y_data[i])
    })

Then there is some SVG manipulation and w,h calcs - these are all in the fiddle.



来源:https://stackoverflow.com/questions/30418892/d3-js-draw-simple-line-graph-starting-from-data-arrays

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