Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  121] [ 7]  / answers: 1 / hits: 18634  / 7 Years ago, mon, march 13, 2017, 12:00:00

i want to add a text message inside my doughnut pie chart. To be more specific i want something like this:
enter



I came across the same issue here in stack overflow by they use chart js in jquery and since i'm new to javascript i got confused. This is how i define my pie chart:



<Doughnut
data={sectorsData}
width={250}
height={250}
options={{
legend: {
display: false
},
maintainAspectRatio: false,
responsive: true,
cutoutPercentage: 60
}}
/>

More From » reactjs

 Answers
187

My example uses the property text on the data to specify the inner text:



const data = {
labels: [...],
datasets: [...],
text: '23%'
};




import React from 'react';
import ReactDOM from 'react-dom';
import {Doughnut} from 'react-chartjs-2';

// some of this code is a variation on https://jsfiddle.net/cmyker/u6rr5moq/
var originalDoughnutDraw = Chart.controllers.doughnut.prototype.draw;
Chart.helpers.extend(Chart.controllers.doughnut.prototype, {
draw: function() {
originalDoughnutDraw.apply(this, arguments);

var chart = this.chart.chart;
var ctx = chart.ctx;
var width = chart.width;
var height = chart.height;

var fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + em Verdana;
ctx.textBaseline = middle;

var text = chart.config.data.text,
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;

ctx.fillText(text, textX, textY);
}
});

const data = {
labels: [
'Red',
'Green',
'Yellow'
],
datasets: [{
data: [300, 50, 100],
backgroundColor: [
'#FF6384',
'#36A2EB',
'#FFCE56'
],
hoverBackgroundColor: [
'#FF6384',
'#36A2EB',
'#FFCE56'
]
}],
text: '23%'
};

class DonutWithText extends React.Component {

render() {
return (
<div>
<h2>React Doughnut with Text Example</h2>
<Doughnut data={data} />
</div>
);
}
};

ReactDOM.render(
<DonutWithText />,
document.getElementById('root')
);

<script src=https://gor181.github.io/react-chartjs-2/common.js></script>
<script src=https://gor181.github.io/react-chartjs-2/bundle.js></script>

<div id=root>
</div>





You'll have to scroll down a bit to see in when running the CodeSnippet due to some weird console error.



It works properly in CodePen though, where I wrote it: http://codepen.io/anon/pen/OpdBOq?editors=1010


[#58574] Friday, March 10, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
ryderalfonsos questions
Mon, Sep 9, 19, 00:00, 5 Years ago
Wed, Feb 13, 19, 00:00, 5 Years ago
Tue, Feb 12, 19, 00:00, 5 Years ago
Fri, Dec 28, 18, 00:00, 6 Years ago
;