How to get specific co-ordinate along Chartjs donut arc - javascript

I need to find the specific x and y coordinates of each arc. Below is a photo illustrating exactly which coordinates I require, color-coded according to each arc. I need those two points of x and y coordinates for every arc element.
Here is a sample arc object(from my own project):
Below is some sample code for this:
const data = {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [{
label: 'Weekly Sales',
data: [18, 12, 6, 9, 12, 3, 9],
backgroundColor: [
'rgba(255, 26, 104, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(0, 0, 0, 0.2)'
],
borderColor: [
'rgba(255, 26, 104, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(0, 0, 0, 1)'
],
borderWidth: 1,
cutout: '70%'
}]
};
const donutArc = {
id: 'donutArc',
afterDraw: (chart) => {
const { ctx, data: { datasets }, } = chart;
datasets.forEach((dataset, i) =>{
chart.getDatasetMeta(i).data.forEach((arc, j) => {
console.log(arc)
})
})
}
}
// config
const config = {
type: 'doughnut',
data,
options: {
plugins: {
legend: {
display: false
}
}
},
plugins: [donutArc]
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
Full code can be found here: https://jsfiddle.net/tpLrxb53/.
I'm pretty sure this involves dealing with the startAngle and endAngle, but I am unable to make sense of them in the documentation here: https://www.chartjs.org/docs/latest/api/classes/ArcElement.html
Any explanation/solutions will be highly appreciated

You can get points on a circle with the formula
x = radius*sin(angle), y = radius*cos(angle)
So I suppose in your code you could do something like
const donutArc = {
id: 'donutArc',
afterDraw: (chart) => {
const { ctx, data: { datasets }, } = chart;
datasets.forEach((dataset, i) =>{
chart.getDatasetMeta(i).data.forEach((arc, j) => {
r1 = arc.innerRadius
r2 = arc.outerRadius
xinner = r1*Math.sin(arc.startAngle)
yinner = r1*Math.cos(arc.startAngle)
xouter = r2*Math.sin(arc.startAngle)
youter = r2*Math.cos(arc.startAngle)
// then I guess here you would draw something
})
})
}
}
This is assuming the origin of the graph is (0,0) and thatstartAngle, outerRadius and innerRadius are what they would appear to be

Related

Chart.js not showing value on top of bars

I started to learn chart.js a while ago and got stuck where the bars are not showing the value on top bars, and how do I add percentage sign after the value?
I use chart.js 3.3.2 cdn btw. Please I need help
let myChart = document.getElementById('myChart').getContext('2d');
const label = ['A','B','C','D','E'];
const datas = [85, 90, 53, 100, 76];
const backgroundColors = [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)'
];
const borderColors = [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)'
]
let iChart = new Chart(myChart, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: 'EQA-Übereinstimmung',
data: datas,
backgroundColor: backgroundColors,
borderColor: borderColors,
borderWidth: 1
}]
},
options: {
responsive:true,
maintainAspectRatio: false,
animation: {
duration: 1,
onComplete: function () {
var chartInstance = this.chart,
myChart = chartInstance.myChart;
myChart.textAlign = 'center';
myChart.fillStyle = "rgba(0, 0, 0, 1)";
myChart.textBaseline = 'bottom';
// Loop through each data in the datasets
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
myChart.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
}
}
});
Someone knows why?
Code was bit outdated, to add a percentage sign to the value you can just add it using string interpolation in the fillText method.
Working sample:
let myChart = document.getElementById('chartJSContainer').getContext('2d');
const label = ['A', 'B', 'C', 'D', 'E'];
const datas = [85, 90, 53, 100, 76];
const backgroundColors = [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)'
];
const borderColors = [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)'
]
let iChart = new Chart(myChart, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: 'EQA-Übereinstimmung',
data: datas,
backgroundColor: backgroundColors,
borderColor: borderColors,
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
animation: {
duration: 1,
onComplete: (x) => {
const chart = x.chart;
var { ctx } = chart;
ctx.textAlign = 'center';
ctx.fillStyle = "rgba(0, 0, 0, 1)";
ctx.textBaseline = 'bottom';
// Loop through each data in the datasets
const metaFunc = this.getDatasetMeta;
chart.data.datasets.forEach((dataset, i) => {
var meta = chart.getDatasetMeta(i);
meta.data.forEach((bar, index) => {
var data = dataset.data[index];
ctx.fillText(`${data}%`, bar.x, bar.y - 5);
});
});
}
}
}
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script>
</body>

How can I add some text in the middle of a half doughnut chart in Chart.JS?

It should look somehow like this:
I already have the chart, just the text is missing. Is there an option to get the text in the middle of the chart?
EDIT: An example of such a graph can be found here: https://jsfiddle.net/wt4260qf/1/
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
rotation: 1 * Math.PI,
circumference: 1 * Math.PI
}
});
Thanks to #DTul, I figured it out. The title configuration is here: https://www.chartjs.org/docs/latest/configuration/title.html.
I've added the following section:
title: {
display: true,
text: 'Custom Chart Title',
position: 'bottom'
}
to the options.
The whole example looks now like that:
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
rotation: 1 * Math.PI,
circumference: 1 * Math.PI,
title: {
display: true,
text: 'Custom Chart Title',
position: 'bottom'
}
}
});
The corresponding fiddle is here: https://jsfiddle.net/ktq8mb0z/
I used this instructions
How can I add some text in the middle of a half doughnut chart in Chart.JS?
some changes for text position and fontsize
var fontSizeToUse = 16;
var centerY = ((chart.chartArea.top + chart.chartArea.bottom) - 80);
http://jsfiddle.net/vencendor/e0c8rgbm/
half-doughnut, or how I call it, a speedometer graph, is now configured with degrees:
var chart = new Chart(canvas, {
type: 'doughnut',
data: ['400', '200'],
options: {
rotation: -90,
circumference: 180,
}
I did this in Chartjs version 3.5.1

ChartJS: Get value from another another Chart

I have two charts, First chart shows the breakup of Shirt sales.
Second is the comparison of Blue Shirt vs Blue Trouser sales.
I want to import the Blue Shirt value from the first Chart to Second chart.
Here is the Code with two charts:
var ctx = document.getElementById("myChart1").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: 'Shirts',
data: [10, 10, 15, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
}
});
var ctx = document.getElementById("myChart2").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Blue Shirts", "Blue Trousers"],
datasets: [{
label: 'Sales',
data: [10, 8],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
}
});
Here is the JSFiddle (https://jsfiddle.net/kingBethal/L8x790fn/15/).
I found this thread describing getting data from click events: Click events on Pie Charts in Chart.js
I made also made a new fiddle here where it logs a chart object containing the chart data on chart click: https://jsfiddle.net/btnL9d2a/16/
myChart1Canvas.onclick = function(evt) {
var activePoints = myChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
// `chartData` will be an object in the format {'Labels' : Array, 'datasets' : Array}.
console.log(chartData);
}
};
chartData.datasets[0].data is an array of the clicked-on chart's data.

ChartJS Bar Graph Gap

I'm using ChartJS to create a simple, static bar graph. As you can see in the picture, there is a small gap between the first x-value (January) and the y-axis. Is there a way to remove that gap and have the first x-axis value start/hug at the y-axis (point: 0,0)? I've looked all over the ChartJS docs and everything I've tried just doesn't work. From my research it seems you should be able to implement this via the options object but I'm at a loss. Any and all help is greatly appreciated!
Thanks!
Set the below option for chart. It will work
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales : {
xAxes : [{
barPercentage : 1,
categoryPercentage : 1
}]
}
}
});
[Sample-Code]
var ctx = document.getElementById("myChart1");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1,
data: [65, 59, 80, 81, 56, 55, 40],
}
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales : {
xAxes : [{
barPercentage : 1,
categoryPercentage : 1
}]
}
}
});

How to draw Horizontal line on Bar Chart Chartjs

I have the following script of drawing bar chart and I wanna add horizontal line on particular y dot. I was trying following example link and I just substituted Chart.types.Line.extend with Chart.types.Bar.extend
but as a result I'm getting can not read property extend of undefined
So can someone help to implement above example which in the link properly or suggest another decision
my source code without horizontal line
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
},
}]
},
}
});
You can use Chart.js plugins to do that. Plugins let you handle specific events such as beforeUpdate or afterDraw and are also easy to implement :
Chart.pluginService.register({
afterDraw: function(chart) {
// Code here will be triggered ... after the drawing
}
});
An easy way to do it is to simply draw a line like you would you on a simple canvas element, after everything is drawn in your chart, using the lineTo method.
Here is a small example (and its related code) of how it would look like :
With the answer from #tektiv, your yAxis always starts at 0.
This is a working example without the use of yAxe.min, so
you can use it (for example, with beginAtZero:false) and the yAxe scales automatically with your data.
Line plugin:
var canvas = document.getElementById("barCanvas");
var ctx = canvas.getContext('2d');
Chart.pluginService.register({
afterDraw: function(chart) {
if (typeof chart.config.options.lineAt != 'undefined') {
var lineAt = chart.config.options.lineAt;
var ctxPlugin = chart.chart.ctx;
var xAxe = chart.scales[chart.config.options.scales.xAxes[0].id];
var yAxe = chart.scales[chart.config.options.scales.yAxes[0].id];
ctxPlugin.strokeStyle = "red";
ctxPlugin.beginPath();
lineAt = yAxe.getPixelForValue(lineAt);
ctxPlugin.moveTo(xAxe.left, lineAt);
ctxPlugin.lineTo(xAxe.right, lineAt);
ctxPlugin.stroke();
}
}
});
Chart:
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
lineAt: 14,
scales: {
yAxes: [{
ticks: {
beginAtZero:false
}
}]
},
}
});

Categories

Resources