How to show negative value in sunburst chart using d3.js?

Member

by rollin , in category: Javascript , a month ago

How to show negative value in sunburst chart using d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , a month ago

@rollin 

To show negative values in a sunburst chart using d3.js, you can use different colors to distinguish between positive and negative values. Here is a simple example code snippet that demonstrates how you can represent negative values in a sunburst chart:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Create the sunburst chart using d3.js
var width = 600;
var height = 600;
var radius = Math.min(width, height) / 2;

var color = d3.scaleOrdinal(d3.schemeCategory10);

var partition = d3.partition()
    .size([2 * Math.PI, radius]);

var arc = d3.arc()
    .startAngle(function(d) { return d.x0; })
    .endAngle(function(d) { return d.x1; })
    .innerRadius(function(d) { return d.y0; })
    .outerRadius(function(d) { return d.y1; });

var svg = d3.select("#chart")
    .append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

// Sample data with negative values
var data = {
  "name": "Root",
  "children": [
    {
      "name": "Category 1",
      "value": 50
    },
    {
      "name": "Category 2",
      "value": -20
    }
  ]
};

var root = d3.hierarchy(data)
    .sum(function(d) { return Math.abs(d.value); });

partition(root);

var g = svg.selectAll("g")
    .data(root.descendants())
    .enter().append("g");

g.append("path")
    .attr("d", arc)
    .style("fill", function(d) { return color((d.children ? d : d.parent).data.name); });

g.append("text")
    .attr("transform", function(d) {
        return "translate(" + arc.centroid(d) + ")";
    })
    .attr("dy", "0.35em")
    .text(function(d) { return d.data.name; });


In this code snippet, we are using positive and negative values in the sample data for two categories. The negative value is represented by a different color in the sunburst chart. You can customize the colors and styles to suit your needs.


Make sure to use negative values as needed in your data and adjust the color mapping and styles accordingly to represent them in the sunburst chart using d3.js.