2

I'm trying to display labels with its value and tooltip in semi donut pie chart using D3 JS. I'm not able to display labels and their values at the simultaneously. And how can I add the tooltip on this chart?

I tried implementing this fiddle. https://jsfiddle.net/SampathPerOxide/hcvuqjt2/6/

var width = 400;
var height = 300; //this is the double because are showing just the half of the pie
var radius = Math.min(width, height) / 2;

var labelr = radius + 30; // radius for label anchor
//array of colors for the pie (in the same order as the dataset)
var color = d3.scale
  .ordinal()
  .range(['#2b5eac', '#0dadd3', '#ffea61', '#ff917e', '#ff3e41']);

data = [
  { label: 'CDU', value: 10 },
  { label: 'SPD', value: 15 },
  { label: 'Die Grünen', value: 8 },
  { label: 'Die Mitte', value: 1 },
  { label: 'Frei Wähler', value: 3 }
];

var vis = d3
  .select('#chart')
  .append('svg') //create the SVG element inside the <body>
  .data([data]) //associate our data with the document
  .attr('width', width) //set the width and height of our visualization (these will be attributes of the <svg> tag
  .attr('height', height)
  .append('svg:g') //make a group to hold our pie chart
  .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')'); //move the center of the pie chart from 0, 0 to radius, radius

var arc = d3.svg
  .arc() //this will create <path> elements for us using arc data
  .innerRadius(79)
  //                                .outerRadius(radius);
  .outerRadius(radius - 10); // full height semi pie
//.innerRadius(0);

var pie = d3.layout
  .pie() //this will create arc data for us given a list of values
  .startAngle(-90 * (Math.PI / 180))
  .endAngle(90 * (Math.PI / 180))
  .padAngle(0.02) // some space between slices
  .sort(null) //No! we don't want to order it by size
  .value(function(d) {
    return d.value;
  }); //we must tell it out to access the value of each element in our data array

var arcs = vis
  .selectAll('g.slice') //this selects all <g> elements with class slice (there aren't any yet)
  .data(pie) //associate the generated pie data (an array of arcs, each having startAngle, endAngle and value properties)
  .enter() //this will create <g> elements for every "extra" data element that should be associated with a selection. The result is creating a <g> for every object in the data array
  .append('svg:g') //create a group to hold each slice (we will have a <path> and a <text> element associated with each slice)
  .attr('class', 'slice'); //allow us to style things in the slices (like text)

arcs
  .append('svg:path')
  .attr('fill', function(d, i) {
    return color(i);
  }) //set the color for each slice to be chosen from the color function defined above
  .attr('d', arc); //this creates the actual SVG path using the associated data (pie) with the arc drawing function

arcs
  .append('svg:text')
  .attr('class', 'labels') //add a label to each slice
  .attr('fill', 'grey')
  .attr('transform', function(d) {
    var c = arc.centroid(d),
      xp = c[0],
      yp = c[1],
      // pythagorean theorem for hypotenuse
      hp = Math.sqrt(xp * xp + yp * yp);
    return 'translate(' + (xp / hp) * labelr + ',' + (yp / hp) * labelr + ')';
  })
  .attr('text-anchor', 'middle') //center the text on it's origin
  .text(function(d, i) {
    return data[i].value;
  })
  .text(function(d, i) {
    return data[i].label;
  }); //get the label from our original data array

I'm trying to achieve this. https://i.stack.imgur.com/BpDhN.png expected grapht

Anas Abu Farraj
  • 1,540
  • 4
  • 23
  • 31
Sampath
  • 153
  • 2
  • 13
  • Hey @sampath, I have exact same requirement. I need to show couple values inside the half circle donut chart. I am using nvd3 and Angular5. Are you able to solve the problem(If yes could you please help me). The answer given below does not include "12345 text" inside the chart. – sandeep Jul 14 '20 at 17:23

2 Answers2

1

First of all, if you console.log the data (from .data(pie)) you used for displaying text label and value, you will noticed that label can only be access via d.data.label instead of data[i].label.

{data: {label: "Frei Wähler", value: 3}, value: 3, startAngle: 1.304180706233562, endAngle: 1.5707963267948966, padAngle: 0.02}

Therefore in order to correctly display both label and value, the code should be:

arcs.append("svg:text")      
    .attr("class", "labels")//add a label to each slice
    .attr("fill", "grey")
    .attr("transform", function(d) {
        var c = arc.centroid(d),
        xp = c[0],
        yp = c[1],
        // pythagorean theorem for hypotenuse
        hp = Math.sqrt(xp*xp + yp*yp);
        return "translate(" + (xp/hp * labelr) +  ',' +
          (yp/hp * labelr) +  ")"; 
     })
    .attr("text-anchor", "middle")    //center the text on it's origin
    .text(function(d, i) { return d.data.value; })
    .text(function(d, i) { return d.data.label; });  

How to add tooltip

As for how to create d3 tooltip, it needs a little of css, html and then add d3 event handling.

1) add the following html to your index.html:

 <div id="tooltip" class="hidden"><p id="tooltip-data"></p></div>

2) add a little bit css to set the div to position:absolute and hide the tooltip with display:none, and gives it a little bit styling per your preference:

<style>
  #tooltip {
    position:absolute;
    background: #ffffe0;
    color: black;
    width: 180px;
    border-radius: 3px;
    box-shadow: 2px 2px 6px rgba(40, 40, 40, 0.5);
  }
  #tooltip.hidden {
    display:none;
  }
  #tooltip p {
    margin: 0px;
    padding: 8px;
    font-size: 12px;
  }

3) We then add mouseover event handler, the idea is when the mouse is over the chart, we will set the top and left properties of the #tooltip css style to where the mouse is, and set the css display property to show the tooltip.

//tooltip
arcs.on("mouseover", function(d) {
  d3.select("#tooltip")
    .style("left", `${d3.event.clientX}px`)
    .style("top", `${d3.event.clientY}px`)
    .classed("hidden", false);
  d3.select("#tooltip-data")
    .html(`Label: ${d.data.label}<br>Value: ${d.data.value}`);
});

arcs.on("mouseout", function(d) {
  d3.select("#tooltip")
    .classed("hidden", true);
});
hcheung
  • 3,377
  • 3
  • 11
  • 23
0

selection.text([value])

If a value is specified, sets the text content to the specified value on all selected elements, replacing any existing child elements.

So you are setting the text content with the value and immediately replacing it with the label.

What you can do is return a combined string from the value and label of your datum in a template literal like this:

.text(function(d, i) { return `${data[i].value} - ${data[i].label}`; })

var width = 400;
var height = 300; //this is the double because are showing just the half of the pie
var radius = Math.min(width, height) / 2;

var labelr = radius + 30; // radius for label anchor
//array of colors for the pie (in the same order as the dataset)
var color = d3.scale.ordinal()
  .range(['#2b5eac', '#0dadd3', '#ffea61', '#ff917e', '#ff3e41']);

data = [{
    label: 'CDU',
    value: 10
  },
  {
    label: 'SPD',
    value: 15
  },
  {
    label: 'Die Grünen',
    value: 8
  },
  {
    label: 'Die Mitte',
    value: 1
  },
  {
    label: 'Frei Wähler',
    value: 3
  }
];

var vis = d3.select("#chart")
  .append("svg") //create the SVG element inside the <body>
  .data([data]) //associate our data with the document
  .attr("width", width) //set the width and height of our visualization (these will be attributes of the <svg> tag
  .attr("height", height)
  .append("svg:g") //make a group to hold our pie chart
  .attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')'); //move the center of the pie chart from 0, 0 to radius, radius

var arc = d3.svg.arc() //this will create <path> elements for us using arc data
  .innerRadius(79)
  //          .outerRadius(radius);
  .outerRadius(radius - 10) // full height semi pie
//.innerRadius(0);


var pie = d3.layout.pie() //this will create arc data for us given a list of values
  .startAngle(-90 * (Math.PI / 180))
  .endAngle(90 * (Math.PI / 180))
  .padAngle(.02) // some space between slices
  .sort(null) //No! we don't want to order it by size
  .value(function(d) {
    return d.value;
  }); //we must tell it out to access the value of each element in our data array

var arcs = vis.selectAll("g.slice") //this selects all <g> elements with class slice (there aren't any yet)
  .data(pie) //associate the generated pie data (an array of arcs, each having startAngle, endAngle and value properties) 
  .enter() //this will create <g> elements for every "extra" data element that should be associated with a selection. The result is creating a <g> for every object in the data array
  .append("svg:g") //create a group to hold each slice (we will have a <path> and a <text> element associated with each slice)
  .attr("class", "slice"); //allow us to style things in the slices (like text)

arcs.append("svg:path")
  .attr("fill", function(d, i) {
    return color(i);
  }) //set the color for each slice to be chosen from the color function defined above
  .attr("d", arc); //this creates the actual SVG path using the associated data (pie) with the arc drawing function

arcs.append("svg:text")
  .attr("class", "labels") //add a label to each slice
  .attr("fill", "grey")
  .attr("transform", function(d) {
    var c = arc.centroid(d),
      xp = c[0],
      yp = c[1],
      // pythagorean theorem for hypotenuse
      hp = Math.sqrt(xp * xp + yp * yp);
    return "translate(" + (xp / hp * labelr) + ',' +
      (yp / hp * labelr) + ")";
  })
  .attr("text-anchor", "middle") //center the text on it's origin
  .text(function(d, i) {
    return `${data[i].value} - ${data[i].label}`;
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<div id="chart" style="width: 330px;height: 200px;"></div>

Edit:

If you want the two text strings to be on separate lines you would have to append some <tspan> elements and position them.

var width = 400;
var height = 300; //this is the double because are showing just the half of the pie
var radius = Math.min(width, height) / 2;

var labelr = radius + 30; // radius for label anchor
//array of colors for the pie (in the same order as the dataset)
var color = d3.scale.ordinal()
  .range(['#2b5eac', '#0dadd3', '#ffea61', '#ff917e', '#ff3e41']);

data = [{
    label: 'CDU',
    value: 10
  },
  {
    label: 'SPD',
    value: 15
  },
  {
    label: 'Die Grünen',
    value: 8
  },
  {
    label: 'Die Mitte',
    value: 1
  },
  {
    label: 'Frei Wähler',
    value: 3
  }
];

var vis = d3.select("#chart")
  .append("svg") //create the SVG element inside the <body>
  .data([data]) //associate our data with the document
  .attr("width", width) //set the width and height of our visualization (these will be attributes of the <svg> tag
  .attr("height", height)
  .append("svg:g") //make a group to hold our pie chart
  .attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')'); //move the center of the pie chart from 0, 0 to radius, radius

var arc = d3.svg.arc() //this will create <path> elements for us using arc data
  .innerRadius(79)
  //          .outerRadius(radius);
  .outerRadius(radius - 10) // full height semi pie
//.innerRadius(0);


var pie = d3.layout.pie() //this will create arc data for us given a list of values
  .startAngle(-90 * (Math.PI / 180))
  .endAngle(90 * (Math.PI / 180))
  .padAngle(.02) // some space between slices
  .sort(null) //No! we don't want to order it by size
  .value(function(d) {
    return d.value;
  }); //we must tell it out to access the value of each element in our data array

var arcs = vis.selectAll("g.slice") //this selects all <g> elements with class slice (there aren't any yet)
  .data(pie) //associate the generated pie data (an array of arcs, each having startAngle, endAngle and value properties) 
  .enter() //this will create <g> elements for every "extra" data element that should be associated with a selection. The result is creating a <g> for every object in the data array
  .append("svg:g") //create a group to hold each slice (we will have a <path> and a <text> element associated with each slice)
  .attr("class", "slice"); //allow us to style things in the slices (like text)

arcs.append("svg:path")
  .attr("fill", function(d, i) {
    return color(i);
  }) //set the color for each slice to be chosen from the color function defined above
  .attr("d", arc); //this creates the actual SVG path using the associated data (pie) with the arc drawing function

const textEl = arcs.append("svg:text")
  .attr("class", "labels") //add a label to each slice
  .attr("fill", "grey")
  .attr("transform", function(d) {
    var c = arc.centroid(d),
      xp = c[0],
      yp = c[1],
      // pythagorean theorem for hypotenuse
      hp = Math.sqrt(xp * xp + yp * yp);
    return "translate(" + (xp / hp * labelr) + ',' +
      (yp / hp * labelr) + ")";
  })
  .attr("text-anchor", "middle"); //center the text on it's origin

textEl.append('tspan')
  .text(function(d, i) {
    return data[i].label;
  });

textEl.append('tspan')
  .text(function(d, i) {
    return data[i].value;
  })
  .attr('x', '0')
  .attr('dy', '1.2em');
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<div id="chart" style="width: 330px;height: 200px;"></div>
ksav
  • 20,015
  • 6
  • 46
  • 66
  • Hi, The values and labels are displaying side by side separated by "-". How can I display values below to the labels like this https://i.imgur.com/kTXeAXt.png ? – Sampath Jan 08 '19 at 06:16
  • Sorry, I really can't see any logic as to how you would display labels like that. Sometimes the number is on the bottom and sometimes its on the right? – ksav Jan 08 '19 at 09:03
  • Check the edited version, it appends the `value` on the next line. – ksav Jan 08 '19 at 09:10
  • Let me know if you have any questions. – ksav Jan 08 '19 at 12:38
  • Very thankful for your answer, the label and value of the second segment in the semi donut chart are not visible. label: 'SPD' and value: 15 are not displaying. Is it due to transform? – Sampath Jan 09 '19 at 04:28
  • No, they are there, but most likely are placed just outside of the SVG viewbox. You should look into drawing your SVG with margins: https://bl.ocks.org/mbostock/3019563 – ksav Jan 09 '19 at 08:59
  • If you change the `labelr` value to 0 you can see that all the labels are there. – ksav Jan 09 '19 at 10:04
  • It is solved, https://jsfiddle.net/SampathPerOxide/hcvuqjt2/12/ . How can I warp the labels so that the labels with more text wont crop. – Sampath Jan 09 '19 at 10:18
  • I think that the problem of warping text could be saved for a new question :) – ksav Jan 09 '19 at 10:23
  • Can you please answer my question regarding label wrap: https://stackoverflow.com/questions/54230158/wrap-labels-in-semi-donut-pie-chart-using-d3-js – Sampath Jan 17 '19 at 06:27
  • @ksav I have a similar requirement - https://stackoverflow.com/questions/62940868/show-text-inside-nvd3-half-circle-donut-chart -- Could you please check once. I did applied the fix given for this question, but it is not working for me. – sandeep Jul 17 '20 at 06:52