how to show text inside a chart - pie and doughnut? - chart.js

I have tried a lot of it, but nothing seems to be working as expected.
I need to show the text inside the pie chart.
For the above, I tried using chartjs-plugin-datalabels but then used a formatter to change a value to a value with a percentage.
formatter: function(value:any, context:Context) {
return Math.floor(value) + '%';
},
But that affected both the data point (i.e: [11,200] is by data, I only need to add a percentage to the first data point and not to the second. Show 11% and 200.)
Code:
import ChartDataLabels,{Context} from 'chartjs-plugin-datalabels';
ChartJS.register(ArcElement, Tooltip, Legend, ChartDataLabels);
export const options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
datalabels: {
formatter: function(value:any, context:Context) {
return Math.floor(value) + '%';
},
color:"white",
font: {
size: 16,
weight:'bold'
}
},
title: {
display: true,
},
legend: {
display: false,
},
},
};
function MyChart(){
return(
<Pie data={dataChart} options={options} />
)
}
In the above code options in the Pie, the component shows a typescript error while using chartjs-plugin-datalabels library.
The expected type comes from property 'options' which is declared here on type 'IntrinsicAttributes & Omit<ChartProps<"doughnut", number[], unknown>, "type"> & { ref?: ForwardedRef<ChartJSOrUndefined<"doughnut", number[], unknown>> | undefined; }'
2: I need to show text in the center of a Doughnut chart but seems impossible with the library and reactchartjs2 don't have a feature to show text in charts. Tried a possible solution at Add text inside the Doughnut chart of the React-Chartjs-2 box to react but none helped.

Related

Is it possible to show each legends aligned with each bar in chart.js

I made a horizontal bar chart using Chart.js. In default setting all the legends are shown all together like this
there is no gap among them. I want to show each legend aligned with each bar like this
I tried so many solutions but none of them worked. Is it possible to show legends right and center aligned with each bar in chart.js?
I am using Chart.js (v.3.7)
The behavior you are looking for can possibly be achieved by using the padding option in the Legend Label Configuration and trying to find the correct value.
This could look something like this:
const chart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
plugins: {
legend: {
display: true,
labels: {
padding: 15 // change according to testing
}
}
}
}
});
You would usually not use a legend for this but instead label the axis directly as described in the link below.
Have a look at the documentation: https://www.chartjs.org/docs/latest/axes/cartesian/#tick-configuration
It provides an example on how to use axis labels like that:
// config
const config = {
type: 'bar',
data,
options: {
indexAxis: 'y',
scales: {
y: {
ticks: {
crossAlign: 'far',
}
}
}
}
};
// setup
const labels = ["Label 1", "Label 2", "Label 3"]
const data = {
labels: labels,
datasets: [{
label: 'My dataset',
borderWidth: 1,
data: [65, 59, 80],
}]
};

chartjs-plugin-error-bars display error-bars without displaying label on a horizontalBar chart

i am trying to add error bars to a horizontal bar chart in chartjs using the chartjs-plugin-error-bars.
It seems that the error bar is tied to a label rather than the actual data, but i dont want do display the label. is there a way to either not declare a label an still have error bars, or just hide the label.
var barChartData = {
labels: ["shouldNotBeDisplayed"],
datasets: [{
data: [
56,
],
errorBars: {
shouldNotBeDisplayed: {plus: 1, minus: 1},
}
}]
};
you can try it out here and see the chart:
https://codepen.io/reckert/pen/rNWmdeK
Thank you in advance
You can filter out tick labels by defining a yAxes.ticks.callback function as follows.
options: {
...
scales: {
yAxes: [{
ticks: {
callback: () => undefined
}
}]
},
For further details, please consult chapter Creating Custom Tick Formats from the Chart.js documentation.

Age pyramid chart using chart.js

I'm trying to create a chart using chart.js like this one (for example):
https://thebreadoflifeblog.files.wordpress.com/2013/01/uk-age-pyramid.png
I tried multiple possibilities and so far, the best one I found is using a simple trick of merging two horizontalBar charts:
But there are actually some problems.
As I said, this is actually two different charts. I would like to have only one object.
I removed the yAxis. I could leave one to display the yAxis labels, but in that case, one of the two graphics will be smaller than the other one. I would like the labels to be displayed between both charts.
The chart on the left is using negative value to achieve the right to left bars. Is there a way to 'revert' an axis ? I saw there is a 'Scale' method, but it seems complicated for just reverting the axis...
I would like to know if there is something I can do to create such chart easier and, most important, as one unique chart.
I ran up against the same problems as you, and managed to fix it using React ChartJS' HorizontalBarChart: but only one ;-)
Try stacking the yAxis and adding two datasets, using the options property
const populationPyramidOptions = {
scales: {
yAxes: [{
stacked: true
}],
xAxes: [{
stacked: false
}]
}
<HorizontalBar data={chartData} options={populationPyramidOptions} />
You can get a pretty good result:
if you use directly chartjs check about the solution here:
https://github.com/nknganda/pyramid_chart_example
The syntax for the options is not compatible with chartjs > 3.x
Below the updated code:
options = {
plugins: {
tooltip: {
intersect: true,
callbacks: {
label: function(context) {
var label = context.dataset.label || '';
var value = context.formattedValue;
var positiveOnly = value < 0 ? -value : value;
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
label += positiveOnly
}
return label;
},
},
},
legend: {
position: "bottom",
},
},
responsive: true,
scales: {
x: {
stacked: false,
ticks: {
beginAtZero: true,
callback: (v) => {
return v < 0 ? -v : v;
},
},
},
y: {
stacked: true,
ticks: {
beginAtZero: true,
},
position: "left",
},
},
indexAxis: 'y'
}
Note that tooltips is now tooltip and inside plugins, alongside with legend.
xAxies and yAxies are x and y and no more a list.
You may find more in the official chartjs doc.
Dataset don't change as you only need to make your values negative.

Chart.js: Make part of labels bold

I want to make a part of the labels in chartJS bold. I've been looking in the documentation but I cant find of any way. I hope there is someone who can help me out if it is possible at all. :) Below is a picture of how I want it to work. (its made in photoshop)
So I want to make the "bar total", "bar 1", "bar 2", "bar 3" and "bar 4" bold so the difference with the hours is more clear.
The labels are set in my code like this:
labels: [["bar total", "150 hour"], ["bar 1", "70 hour"], ["bar 2", "30 hour"], ["bar 3", "40 hour"], ["bar 4", "10 hour"]],
Iam using ChartJS version 2.3.0.
Any ideas?
I'm not too familiar with chartJS but I do believe that you can add the following :
Chart.defaults.global.defaultFontStyle = 'Bold'
OR
options: {
scale: {
pointLabels :{
fontStyle: "bold",
}
}
}
References:
1) Chart js. How to change font styles for "labels" array?
Hope this helps!
Joel
The labels are actually denoted by ticks , please try below solution.
public barChartOptions = {
scales: {
xAxes: [{
/* For changing color of x-axis coordinates */
ticks: {
fontSize: 18,
padding: 0,
fontColor: '#000'
}
}]
}
};
Hopefully this will help you.
You need to use directly the UTF-8 characters. I am working on different graphs now and the tool which is available at https://yaytext.com/bold-italic/ helped me a lot.
For example, the following words were created by the tool, see the source code, they are without any HTML formatting:
Hello World!
π‡πžπ₯π₯𝐨 𝐖𝐨𝐫π₯𝐝!
𝗛𝗲𝗹𝗹𝗼 π—ͺ𝗼𝗿𝗹𝗱!
π»π‘’π‘™π‘™π‘œ π‘Šπ‘œπ‘Ÿπ‘™π‘‘!
I just tried this. Any acceptable values from the link below should work
https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight
Ex:
Chart.defaults.global.defaultFontStyle = '600';
If you are looking for a fancy label with value processing and with some sign, bold label etc.
labels: {
render:function (args) {
if (args.value != 0)
return +(parseFloat(args.value).toFixed(2)) + "hrs";
},
fontStyle: "bold",
fontColor: 'black',
position : 'outside'
}
I hope this helps.
The fontStyle value should be present inside the ticks object (in case of react-chartjs-2).
const options = {
scales: {
xAxes: [
{
ticks: {
fontColor: '#2c2c2c', // X-Axis font color
fontStyle: 'bold', // X-Axis font style
},
},
],
}
}
Chart.defaults.global.defaultFontColor = 'red';
let chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
legend: {
labels: {
// This more specific font property overrides the global property
fontColor: 'black'
}
}
}
});
You can find in http://www.chartjs.org/docs/latest/general/fonts.html
I hope it will be help you.

I want to hide the label in a tooltip because it shows undefined

I am using chart.js to show a line chart. How can I hide a tooltip label for a chart.js line chart? The label in the tooltip is showing undefined so I want to hide the label (please see the screenshot)?
Perhaps there is a way to modify tooltip where I can show only the legends value in tooltip? My code is as follows:
myLine = new Chart(ctx).Line(lineChartData, {
type: 'line',
responsive: true,
scaleShowGridLines : false,
bezierCurve : false,
animationEasing: "linear",
tooltipEvents: ["mousemove", "touchstart", "touchmove"],
showTooltips: true,
scaleLineColor: "rgba(0,0,0,.8)",
});
Just set the tooltipTitleFontSize to 0 in your options.
Preview
Script
myLine = new Chart(ctx).Line(lineChartData, {
...
tooltipTitleFontSize: 0
});
I know I am late, but I guess it still has merit to add this one.
check this : https://stackoverflow.com/a/44632748/12061669
It uses a function to hide the title:
options:{
tooltips:{
callbacks:{
title: ()=>{}
}
}
}
Setting the title's font size to zero is not ideal as you will still see an (ugly) extra space on top of the tooltip, as if the title line is still there - which honestly is what you'd expect.
Instead, I used Yumin Gui's answer but had to return null for it to work:
`
tooltips: {
callbacks: {
title: () => null,
},
},
The result is exactly as in the pie charts (which does not have a title in its default tooltips).
To hide the tooltip title/label, it should be added in the options object for that chart as follows:
options: {
plugins: {
tooltip: {
callbacks: {
title : () => null // or function () { return null; }
}
}
}
}
Do refer to the documentation to understand better that it should be handled with a custom callback function, and it is not a config that can be set in options directly.
The accepted answer won't work in newer versions of chart.js, as Aman said in comments, what you can use now is this:
tooltips: { titleFontSize: 0 }
Example:
var bar_chart = document.getElementById('bar_canvas').getContext('2d');
window.myBar = new Chart(bar_chart, {
type: 'bar',
data: bar_chart_data,
options: {
tooltips: {
titleFontSize: 0,
bodyFontSize: 14,
}
}
});