Data Labels wrongly positioned on bar chart - chartjs - javascript

I'm using chartjs-plugin-datalabels to show values on chart, but the labels are not centered.
The main part is in the datasets.datalabels where I can override default settings, which sets to center anyway, but wanted to show where its done.
I have tried positione it to the right, but as the value getting bigger, the datalabel is less centered.
Chart.register(ChartDataLabels);
const data_tafkidim_cat_count = {
labels: window.TafkidimCatCount.map((el) => el.TafkidCat.split(' ')).slice(0, pagination['tafkidim_cat_count'].show),
datasets: [
{
data: window.TafkidimCatCount.map((el) => el.Total),
backgroundColor: Setcolors(),
borderColor: Setcolors(1),
borderWidth: 1,
datalabels: {
anchor: 'center',
align: 'center',
},
},
],
};
const config_tafkidim_cat_count = {
type: 'bar',
data: data_tafkidim_cat_count,
options: {
scales: {
x: {
grid: {
borderColor: '#829AB1',
},
ticks: {
color: '#627D98',
},
reverse: true,
},
y: {
grid: {
borderColor: '#829AB1',
},
beginAtZero: true,
ticks: {
color: '#627D98',
},
},
},
plugins: {
title: {
text: TL['tafkidim_cat_count'],
padding: {
bottom: 20,
},
},
legend: {
display: false,
},
tooltip: {
callbacks: {
title: (context) => {
return context[0].label.replaceAll(',', ' ');
},
},
},
},
},
};
const tafkidim_cat_count = new Chart('#tafkidim-cat-count'.Element().getContext('2d'), config_tafkidim_cat_count);

solved it with
textAlign = "center"
apparently the default is "start".

Related

Selection zoom not working for Area chart in Apexchart for React Js

I have implemented an Area Chart using Apexchart for React Js. I have set options using useState. When I am updating the options by updating the state. When I am using selection zoom, the charts get zoomed and then gets reset within less than a second. Can someone help me with it? Thanks in advance.
setOptions1({
dataLabels: {
enabled: false,
},
chart: {
id: 'chartId1',
width: "100%",
zoom: {
enabled: true,
type: 'x',
// autoScaleYaxis: true,
},
toolbar: {
show: true,
tools: {
reset: true | '<img src="/static/icons/reset.png" width="20">',
customIcons: openModal ? [] : [{
icon: `<img src=${fullScreen} width="13">`,
index: 6,
title: 'full screen',
class: 'custom-icon-css',
click: function (chart, options, e) {
setOpenModal(true);
setOpenModalAreaChart(true);
setModalChartdata(options.globals.chartID)
}
}]
},
autoSelected: 'zoom'
},
},
xaxis: {
categories: year1,
min: 1,
max: 17
},
yaxis: [
{
title: {
text: 'Scale: in Millions ($)',
style: {
color: "rgb(55, 61, 63)",
fontSize: " 13px",
fontWeight: "400",
fontFamily: 'Montserrat, sans- serif'
},
},
},
],
legend: {
show: true,
showForSingleSeries: true
},
tooltip: {
y: {
formatter: function (val, index) {
return '$' + val;
}
}
},
stroke: {
show: true,
curve: 'smooth',
lineCap: 'butt',
colors: undefined,
width: 2,
},
responsive: [
{
breakpoint: 650,
options: {
chart: {
width: '50%'
}
},
},
{
breakpoint: 500,
options: {
chart: {
width: '30%'
}
},
}
],
})
}

Having multiple doughnut charts on the same canvas

I have a main doughnut chart and would like to implement another 2 smaller doughnut chart but I am having trouble implementing multiple doughnut charts on the same canvas as my main chart.
How do I solve this issue? Do I just need another chart instance with a .update()?
Something like this:
this is my current code:
var config = {
type: 'doughnut',
data: {
labels: legend,
datasets: [{
backgroundColor: ['rgb(204,0,0)', 'rgb(241,194,50)', 'rgb(41,134,204)', 'rgb(106,168,79)', 'rgb(255,62,153)'],
data: stats,
}]
},
plugins: [hoverLabel, drawBackground],
options: {
radius: this.radius,
hoverOffset: 30,
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: "Top 5 causes of death in " + country,
color: 'rgb(0,0,0)',
align: 'center',
padding: 15,
font: {
size: 25
}
},
legend: {
position: 'right',
title: {
display: true,
color: 'rgb(0,0,0)',
text: 'Legend',
font: {
weight: 'bold',
size: 20
},
},
//Changing mouse cursor over legend item
onHover: (event, chartElement) => {
event.native.target.style.cursor = 'pointer';
},
onLeave: (event, chartElement) => {
event.native.target.style.cursor = 'default';
},
labels: {
color: 'rgb(0,0,0)',
usePointStyle: true,
padding: 20,
textAlign: 'left',
font: {
size: 15,
weight: 'bold'
}
}
}
}
}
};

Chart JS Tooltip Currency Problem - Stacked Bar Chart

I use ChatJS and i want to add an € Symbol after every number in the Tooltip.
On my most charts it works perfectly but the Stacked Bar Chart makes me problems.
Here is an example Code like mine (Just a basic Example)
var barChart = new Chart(ctx_barChart, {
type: 'bar',
data: {
labels: ["Fruits"],
datasets: [{
label: [
["Apple"]
],
data: [12],
backgroundColor: 'blue',
barThickness: 80,
},
{
label: ["Banana"],
data: [15],
backgroundColor: 'red',
barThickness: 80,
},
]
},
options: {
maintainAspectRatio: false,
indexAxis: 'y',
responsive: true,
scales: {
x: {
stacked: true,
display: false,
},
y: {
stacked: true,
display: false,
mirror: true,
}
},
plugins: {
tooltip: {
callbacks: {
label: function(context) {
let label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
label += new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'EUR'
}).format(context.parsed.y);
}
return label;
}
}
},
legend: {
display: false
},
title: {
display: false,
},
},
},
});
The tooltips both show 0,00$, but not my Values 12 and 15. Anyone have an suggestiont?
You should use context.parsed.x instead of context.parsed.y since it's a horizontal bar chart.
Please take a look at your amended code and see how it works.
new Chart('barChart', {
type: 'bar',
data: {
labels: ["Fruits"],
datasets: [{
label: "Apple",
data: [12],
backgroundColor: 'blue',
barThickness: 80,
},
{
label: "Banana",
data: [15],
backgroundColor: 'red',
barThickness: 80,
},
]
},
options: {
maintainAspectRatio: false,
indexAxis: 'y',
responsive: true,
scales: {
x: {
stacked: true,
display: false,
},
y: {
stacked: true,
display: false,
mirror: true,
}
},
plugins: {
tooltip: {
callbacks: {
label: ctx => ctx.dataset.label + ': ' + new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(ctx.parsed.x)
}
},
legend: {
display: false
},
title: {
display: false,
},
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="barChart" height="100"></canvas>

chartjs-plugin-datalabels not showing on stacked horizontal bar

I'm trying to make a simple horizontal stacked bar chart and add labels to it. I'm not sure what I'm doing wrong here, any input would be appreciated.
I can make it work by downgrading to a much lower version of chart.js and the datalabel plugin.
Here is a jsfiddle:
https://jsfiddle.net/chrispret/szLgyu2j/24/
And some test code...
const testData = {
set1: '4',
set2: '3',
set3: '1',
set4: '3',
};
const data = {
labels: ["test"],
datasets: [
{
label: 'set1',
data: [testData.set1],
backgroundColor: 'red',
datalabels: {
anchor: 'center',
align: 'center',
}
},
{
label: 'set2',
data: [testData.set2],
backgroundColor: 'blue',
datalabels: {
anchor: 'center',
align: 'center',
}
},
{
label: 'set3',
data: [testData.set3],
backgroundColor: 'green',
datalabels: {
anchor: 'center',
align: 'center',
}
},
{
label: 'set4',
data: [testData.set4],
backgroundColor: 'gray',
datalabels: {
anchor: 'center',
align: 'center',
}
}
]
};
const config = {
type: 'bar',
data: data,
options: {
aspectRatio: 15 / 3,
indexAxis: 'y',
elements: {
bar: {
borderWidth: 2,
}
},
responsive: true,
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
},
plugins: {
datalabels: {
color: 'white',
font: {
weight: 'bold'
},
formatter: Math.round
},
legend: {
position: 'right',
},
title: {
display: true,
text: 'Chart.js Horizontal Bar Chart'
},
}
},
};
const myChart = new Chart(
document.getElementById('chartDemo'),
config
);
Since version 1.x, the chartjs-plugin-datalabels plugin no longer registers itself automatically. It must be manually registered either globally or locally as described here.
Therefore, to make it work, you could add the following line to your code prior to create the chart.
Chart.register(ChartDataLabels);
Please take a look at your amended code and see how it works.
const testData = {
set1: '4',
set2: '3',
set3: '1',
set4: '3',
};
const data = {
labels: ["test"],
datasets: [{
label: 'set1',
data: [testData.set1],
backgroundColor: 'red'
},
{
label: 'set2',
data: [testData.set2],
backgroundColor: 'blue'
},
{
label: 'set3',
data: [testData.set3],
backgroundColor: 'green',
datalabels: {
anchor: 'center',
align: 'center'
}
},
{
label: 'set4',
data: [testData.set4],
backgroundColor: 'gray'
}
]
};
const config = {
type: 'bar',
data: data,
options: {
aspectRatio: 15 / 3,
indexAxis: 'y',
elements: {
bar: {
borderWidth: 2
}
},
responsive: true,
scales: {
x: {
stacked: true
},
y: {
stacked: true
}
},
plugins: {
datalabels: {
anchor: 'center',
align: 'center',
color: 'white',
font: {
weight: 'bold'
},
formatter: Math.round
},
legend: {
position: 'right'
},
title: {
display: true,
text: 'Chart.js Horizontal Bar Chart'
},
}
},
};
Chart.register(ChartDataLabels);
const myChart = new Chart(
document.getElementById('chartDemo'),
config
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="chartDemo"></canvas>
Add the labels to the labels array.
const data = {
labels: ["hrZone1","hrZone2","hrZone3","hrZone4"],
datasets: [
{
label: 'peak',
data: [hrData.peak,0,0,0],
backgroundColor: 'red'
},
{
label: 'cardio',
data: [0,hrData.cardio,0,0],
backgroundColor: 'blue'
},
{
label: 'fatBurn',
data: [0,0,hrData.fatBurn,0],
backgroundColor: 'green'
},
{
label: 'under',
data: [0,0,0,hrData.under],
backgroundColor: 'gray'
}
]
};

How do I fix over limit y axis value in ChartJS

Hello Everyone!
I am using chartjs-plugin-datalabels to prevent unhoverable tiny values by displaying the value above his bar, but when one of them has the highest value the datalabels exceed the limit of the chart container
UPDATE:
Also, you can use suggestedMax option and I think it's better than giving a padding
const options = {
plugins: {
datalabels: {
color: '#374774',
font: { family: 'MyriadSemiBold', size: 14 },
align: 'end',
anchor: 'end',
formatter: (value) => {
if (value > 0) {
return localizeNumber(value)
}
return ''
},
},
legend: { display: false },
},
scales: {
x: {
grid: { lineWidth: 0 },
ticks: {
display: false,
},
},
y: {
// Highest value in your datasets
suggestedMax: highestValue > 0 ? highestValue + 1e5 : 10,
grid: { color: '#DFDFDF' },
ticks: {
callback: (value) => {
return abbreviateNumber(value)
},
font: { family: 'MyriadRegular', size: 14 },
color: '#374774',
},
},
},
}
The easiest solution is to add padding to the top of your chart (simple sample below). You may also play around with the datalabel plugin's clamping options to adjust the position of the label when it's outside the chart.
const layoutOptions = {
padding: {
top: 30 // Add 30 pixels of padding to top of chart.
}
};
const data = {
labels: ['Large', 'Small'],
datasets: [{ data: [100, 2] }]
};
const config = {
type: 'bar',
data: data,
options: {
layout: layoutOptions,
scales: { y: { beginAtZero: true, max: 100 } },
plugins: {
legend: { display: false },
datalabels: { anchor: 'end', align: 'top' }
}
},
};
new Chart(document.getElementById('myChart'), config);
#myChart {
max-height: 180px;
}
<div>
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0"></script>
<script>Chart.register(ChartDataLabels);</script>

Categories