2

I have pie chart with custom label and percentage. Issue is Label and percentage appears in same line. I need to break percentage and label into two lines. Label percentage

I have try <br> and \n but did not work. Please help

var names = ['', 'Home Loans', 'Auto Loans'];

var data = {
  series: [3, 5, 4]
};

var sum = function(a, b) {
  return a + b
};

new Chartist.Pie('.ct-chart', data, {
  labelInterpolationFnc: function(value, idx) {
    var percentage = Math.round(value / data.series.reduce(sum) * 100) + '%';
    return names[idx] + '\n' + percentage;
  }
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/chartist/0.11.0/chartist.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartist/0.11.0/chartist.min.js"></script>
<div class="ct-chart"></div>

enter image description here

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Nimra Waseem
  • 59
  • 12

2 Answers2

0

Sorry, but for now, using this library, it's impossible.

The only option to break a line in svg is to split it to tspans.
(See How to display multiple lines of text in SVG?).

To do this, chartist have to change their code of labelInterpolationFnc call: instead of using text the need to allow html so you could split the text by yourself.

Something like:

labelInterpolationFnc: function(value, idx) {
  var percentage = Math.round(value / data.series.reduce(sum) * 100) + '%';
  return `
    <tspan>${names[idx]}</tspan>
    <tspan>${percentage}</tspan>
  `;
}
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
  • Sorry, maybe I didn't be clear enough. For now, it's impossible: `To do this, chartist have to change their code of labelInterpolationFnc call` – Mosh Feu Dec 24 '18 at 06:32
0

Mosh Feu's answer didn't work me, 'cause Chartist rendered < tspan>...</ tspan > content like a simple string and not like an HTML-code.

This issue gave me an idea, which consist in draw event handler:

.on('draw', function(data) {

    if (data.type === 'label') {
        let textHtml = ['<p>', data.text, '</p>'].join('');

        let multilineText = Chartist.Svg('svg').foreignObject(
            textHtml,
            {
                style: 'overflow: visible;',
                x: data.x - 30,
                y: data.y - 50,
                width: 130,
                height: 20
            },
            'ct-label'
        );
        data.element.replace(multilineText);
    }

Codepen for your case is here.

Boolean_Type
  • 1,146
  • 3
  • 13
  • 40