0 fill zero values ​​with data d3

I am working on a multi-line chart in D3, but I have some problems with rendering. I am trying to make two lines with data that look like this:

[ { key:"line 1", values: [ {x:1, y:1}, {x:2, y:2} ] }, { key:"line 2" , values: [ {x:1, y:1}, {x:2, y:2}, {x:3, y:3} ] } ] 

"line 2" is displayed just fine, but "line 1" stops rendering at x = 2. I understand that my dataset may be considered incomplete, but I was curious if there was a way to set the default value to 0, are there spaces or zero values for x? In particular, in this example, I want the string "1" to display y = 0, where x = 3.

+6
source share
1 answer

D3 and NVD3 do not have functions for this. It is best to insert the missing values. Some CoffeeScript, which uses some Underscore utilities, but d3 had a lot of the same features, so you don't have to depend on Underscore if you don't need it. First you get a list of domain values, then insert your missing values.

The getDomainValues ​​method accepts data and sizes (key) and retrieves all values ​​to obtain a set of domain values. If you have data such as:

  key : a values : [ {x: 4, y:1}, {x: 5, y:1}, {x: 7, y:1} ] key : b values : [ {x: 1, y:10}, {x: 2, y:5}, {x: 3, y:0} ] 

He will return:

 [1,2,3,4,5,7] 


 getDomainValues = (data, dimension) -> _.uniq _.flatten _.map data, (item) -> _.pluck(item.values, dimension) 

The insertValues ​​method inserts default values ​​(most often 0) for dimension values ​​that are not in the value array. It is sorted by size. If you have data such as:

  key : a values : [ {x: 4, y:1}, {x: 2, y:1}, {x: 1, y:1} ] 

And provided the domain [0, 1,2,3,4,5] and the value -10 you got:

  key : a values : [ {x: 0, y:-10}, {x: 1, y:1}, {x: 2, y:1}, {x: 3, y:-10}, {x: 4, y:1}, {x: 5, y: -10}] 


 insertValues = (data, value, dimension, metric, domain)-> defaults = {} for item in domain v = {} v[dimension] = item v[metric] = value defaults[item] = v _.each data, (item) -> vals = _.groupBy( item.values, (i) -> i[dimension]) vals = _.flatten _.values _.defaults vals, defaults vals = _.sortBy vals, dimension item.values = vals data 

So you can name them as follows:

 data = [ { key:"line 1", values: [ {x:1, y:1}, {x:2, y:2} ] }, { key:"line 2" , values: [ {x:1, y:1}, {x:2, y:2}, {x:3, y:3} ] } ] domain = getDomainValues data, 'x' filledData = insertValues data, 0, 'x', 'y', domain 

Take a look at JavaScript: https://gist.github.com/FaKod/e6724675e4ebaf9f8fa4

+2
source

Source: https://habr.com/ru/post/947057/


All Articles