Back

Technologies:

javascriptjavascript
avatar
Tolerim
a day ago

Is there a simpler way to understand the array hierarchy of items within a treemap using plotly.js?

One issue I'm facing is how to customize item hierarchies in the treemap feature of plotly.js, even after reading through the documentation. My preferred hierarchy is a nested one expressed through code that resembles a tree. Here's an example:
{
   parent:{ "topItem"},
   topItem: {"one","two","three"},   /* children of top-item */
   one:{"something"},   /* child of "one" */
   two: {"thing", "whatever"} /* a couple of children of "two" */

} 
Although there may be superior ways of accomplishing this, I'm more comfortable with this structure since it mirrors my thought process for nested data relationships. However, the way data and rendered output are related in plotly.js' treemap example code confuses me, and I'm having difficulty conceptualizing it. The example features arrays that depict nested item relationships, as seen here:
data = [{
      type: "treemap",
      labels: ["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
      parents: ["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve" ]
}]

Plotly.newPlot('myDiv', data)
This produces the hierarchy visible here: https://codepen.io/pen. At present, I'm unsure how to modify this layout, such as adding three children to the "Cain" block. If you have any insights to improve my understanding, I'd appreciate it. Thank you.
Answers(1)
avatar
Tolerim
a day ago
Verified Answer
The parents array in Plotly.js treemap charts is used to define the hierarchy of items. Each element of the parents array corresponds to an element in the labels array. The element at index i in the parents array indicates the parent of the element at index i in the labels array. In the example you provided, "Eve" is the parent of "Cain", and "Cain" is the parent of "Abel" and "Awan". If you wanted to add three children to the "Cain" block, you would need to add three new elements to the labels array, and three new elements to the parents array. The new elements in the labels array would be the labels for the children, and the new elements in the parents array would be "Cain", indicating that they are children of the "Cain" block. Here is an example of what the modified data array would look like:
data = [{
    type: "treemap",
    labels: ["Eve", "Cain", "Abel", "Awan", "New Child 1", "New Child 2", "New Child 3", "Seth", "Enos", "Noam", "Enoch", "Azura"],
    parents: ["", "Eve", "Cain", "Cain", "Cain", "Cain", "Cain", "Eve", "Eve", "Seth", "Awan", "Eve" ]
}]

Plotly.newPlot('myDiv', data)
In this modified example, "Abel", "Awan", "New Child 1", "New Child 2", and "New Child 3" are children of "Cain". The indices of the new elements in the labels array are 2, 3, 4, 5, and 6, and their corresponding parents are all "Cain".
;