D3js: When to use .datum() and .data()?

前端 未结 3 1910
清酒与你
清酒与你 2021-01-31 08:38

I often see .datum when an area chart is used. For example:

svg = d3.select(\"#viz\").append(\"svg\").datum(data)

Are there any

3条回答
  •  别那么骄傲
    2021-01-31 09:29

    Others linked to the tutorial, but I think the API reference on selection.datum gives the accepted answer:

    Gets or sets the bound data for each selected element. Unlike the selection.data method, this method does not compute a join (and thus does not compute enter and exit selections).

    Since it does not compute a join, it does not need to know a key function. Therefore, notice the signature difference between the two, only the data function accepts a key function

    • selection.datum([value])
    • selection.data([values[, key]])

    I think the tutorial for data gives another more basic difference which is analogous to the meaning of the words "data" and "datum". That is, "data" is plural, the "datum" is singular. Therefore, data can be joined in two ways:

    Joined to groups of elements via selection.data.

    Assigned to individual elements via selection.datum.

    @Hugolpz' gist gives nice examples of the significance of "groups" vs "individuals". Here, json represents an array of data. Notice how datum binds the entire array to one element. If we want to achieve the same with data we must first put json inside another array.

    • var chart = d3.select("body").append("svg").data([json])
    • var chart = d3.select("body").append("svg").datum(json)

提交回复
热议问题