Applying Callback To One Y-Axis - javascript

I have this part of my chartjs code below, I would like to make the data on y-axis-b always have two decimals even if it's "0", I did some research and found this callback here on Stackoverflow, but it applies to both y-Axes, how can I have it apply to only y-axis-b? Thanks!
options: {
tooltips: {
mode: 'index',
callbacks: {
label: (tooltipItem, data) => {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
return label + ' ' + (Math.round(tooltipItem.yLabel * 100) / 100).toFixed(2);
}
}
},
scales: {
xAxes: [{
barPercentage: 0.6,
ticks: {
min: 0
}
}],
yAxes: [{
ticks: {
reverse: false,
suggestedMax:100,
beginAtZero: true,
},
position: "right",
id: "y-axis-b",
scaleLabel: {
display: true,
}
}, {
gridLines : {
drawOnChartArea: false
},
scaleLabel: {
display:true,
},
position: "left",
id: "y-axis-a",
ticks: {
suggestedMax: 1500,
suggestedMin: -1500
}
}]
}
}

Instead of using label in options/tooltips/callbacks, use ticks in options/scales/y like this example.
So your code becomes:
options: {
scales: {
y: {
ticks: {
// Customize your label here
callback: function(value, index, values) {
return value.toFixed(2);
}
}
}
}
}

Related

chart js 3.9.1 - barchart - margin left

how do i reduce the space between the bar and the y scale? I tried with padding but it doesn't work
Thanks
This is my configuration,I upload the data at runtime and update the graph
Chart.register(ChartDataLabels);
var options = {
tooltips: {
enabled: false
},
plugins:
{
datalabels:
{
color: 'white'
},
legend: {
position: 'top', labels:
{
font: {size: 10},
usePointStyle: true
}
}
},
scales:
{
x: {
barPercentage: 6.5,
categoryPercentage: 0.1
},
y: {
barPercentage: 1,
categoryPercentage: 1,
beginAtZero: true,
grace: '3%',
ticks: {
beginAtZero: true
}
}
}
};
var barChart = new Chart(document.getElementById("chart3"), {
type: 'bar',
data:
{
labels: [""]
},
options:options
});
for (i = 0; i < parsed[0].length; i++)
{
barChart.data.datasets.push({ label: parsed[0][i].label, backgroundColor: parsed[0][i].backgroundColor, data: ["" + parsed[0][i].data + ""], pointStyle:'circle' });
}
barChart.update();
The issue sounds being related to categoryPercentage and barPercentage options that you are set in the axis but this is not the right place.
Move those options in the chart.options and it should work.
Try using categoryPercentage: 1.
var options = {
categoryPercentage: 1,
plugins:
{
datalabels:
{
color: 'white'
},
legend: {
position: 'top', labels:
{
font: {size: 10},
usePointStyle: true
}
}
tooltip: {
enabled: false
},
},
scales:
{
y: {
beginAtZero: true,
grace: '3%',
}
}
};

Javascript Canvas labels too long

When I use small version numbers (the label), my canvas is shown as it should:
But when my labels get too long it starts to look very unreadable, and I don't know how to avoid this?:
Can I change my options to solve this, if yes, how?
Here is my javascript function, and nameArray is the array with version numbers, and I have to shorten these somehow.
function renderBarChart(nameArray, passArray, failArray, divId, title) {
var ctx = document.getElementById(divId).getContext('2d');
var newChart = new Chart(ctx, {
type: 'bar',
data: {
labels: nameArray,
datasets: [{
label: 'Passed',
data: passArray,
backgroundColor: 'rgb(150,238,144)'
},
{
label: 'Failed',
data: failArray,
backgroundColor: 'rgb(204,0,0)'
}
]
},
options: {
title: {
display: true,
text: title
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
responsive: false,
maintainAspectRatio: false,
scales: {
xAxes: [{
stacked: true,
ticks: {
stepSize: 1,
min: 0,
autoSkip: false
}
}],
yAxes: [{
stacked: true,
ticks: {
maxTicksLimit: 5,
min: 0
}
}]
}
}
});
}
EDIT 1
Right now I'm trying to do something like this, but I can't make it work.
Inspiration form: How to shorten Chart.js label
function renderBarChart(nameArray, passArray, failArray, divId, title) {
var ctx = document.getElementById(divId).getContext('2d');
var newChart = new Chart(ctx, {
type: 'bar',
data: {
labels: nameArray,
datasets: [{
label: 'Passed',
data: passArray,
backgroundColor: 'rgb(150,238,144)'
},
{
label: 'Failed',
data: failArray,
backgroundColor: 'rgb(204,0,0)'
}
]
},
options: {
title: {
display: true,
text: title
},
tooltips: {
enabled: true,
mode: 'label',
callbacks: {
title: function(tooltipItems, data) {
var idx = tooltipItems[0].index;
return 'Title:' + data.labels[idx]; //do something with title
},
label: function(tooltipItems, data) {
//var idx = tooltipItems.index;
//return data.labels[idx] + ' €';
return tooltipItems.xLabel + ' €';
}
}
},
hover: {
mode: 'nearest',
intersect: true
},
responsive: false,
maintainAspectRatio: false,
scales: {
xAxes: [{
stacked: true,
ticks: {
stepSize: 1,
min: 0,
autoSkip: false,
callback: function(value) {
if (value.length > 4) {
return value.substr(0, 4) + '...'; //truncate
} else {
return value
}
},
}
}],
yAxes: [{
stacked: true,
ticks: {
maxTicksLimit: 5,
min: 0
}
}]
}
}
});
}

ChartJS How to set color to just one bar

I have this barChart and I'm with difficult to set a color by script to just one bar of the index.
Bellow is my chartbar code:
var ctx = document.getElementById("myBarChart");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: "Valor",
backgroundColor: "rgba(2,117,216,1)",
borderColor: "rgba(2,117,216,1)",
data: [],
}],
},
options: {
plugins: {
datalabels: {
anchor: 'end',
align: 'top',
formatter: function (value, context) {
if (value != 0) {
return new Date(value * 1000).toISOString().substr(11, 8);
} else {
value = " "
return value;
}
},
font: {
weight: 'bold'
}
}
},
responsive: true,
tooltips: {
/* intersect: false, */
callbacks: {
title: function (tooltipItem, data) {
return data['labels'][tooltipItem[0]['index']];
},
label: function (tooltipItem, data) {
return new Date(parseInt(data['datasets'][0]['data'][tooltipItem[
'index']]) * 1000).toISOString().substr(11,
8);
},
},
},
scales: {
xAxes: [{
time: {
unit: 'month'
},
gridLines: {
display: false
},
}],
yAxes: [{
ticks: {
min: 0,
suggestedMax: 36000,
stepSize: 3600,
beginAtZero: true,
},
}],
},
}
});
I have tried this:
myBarChart.data.datasets[0].backgroundColor[0]
But it doesnt work.
If someone know how to do this in the last version of the chartjs, please help me.
You can provide an array to the backgroundColor property. In this array you can fill it with the default color except for the index where you want the bar to be a different collor

Zoom-In functionality in histogram using Chart.js

I have a created a histogram using chart.js. (Referring Make a Histogram in Chart.js). Now i need a zoom in functionality because by default if i am enabling zoom in chart labels and bars are not in-sync. And my data is too much in chart. so i need with width of bar.
This is my config object.
const config: any = {
type: 'bar',
data: {
labels: xLabelx,
datasets: [ { label: 'Count', backgroundColor: 'rgba(215, 239, 252,0.5)', data: NumberOfVehicle,
borderColor: '#37B1F0', borderWidth: 0.5, hoverBackgroundColor: '#66bcff' } ]
},
options: {
tooltips: {
mode: 'label',
bodyFontSize: 12,
opacity: 0.5,
borderWidth: 5,
callbacks: {
title: (tooltipItems, data) => { return ''; },
label(tooltipItem, data) {
const label = data.datasets[tooltipItem.datasetIndex].label;
const value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return label + ': ' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '');
} } },
pan: { enabled: true, mode: 'xy', drag: true, speed: 10, threshold: 10 },
zoom: { enabled: true, drag: false, mode: 'x' },
maintainAspectRatio: false,
responsive: false,
legend: {
display: true,
onHover: (event, legendItem) => { document.getElementById('myChart').style.cursor = 'pointer'; },
labels: { fontSize: 14 }},
hover: {
onHover: (e, el) => { $('#myChart').css('cursor', el[0] ? 'pointer' : 'default'); }
},
scales: {
xAxes: [
{ display: false, barPercentage: 1.25, ticks: { max: xLabelx[xLabelx.length - 2] }},
{ display: false, ticks: { autoSkip: false, max: xLabelx[xLabelx.length - 1]}},
{ scaleLabel: { display: true, labelString: 'Range', fontFamily: 'Roboto', fontSize: 14 }}
],
yAxes: [
{ scaleLabel: { display: true, labelString: 'No. of model', fontFamily: 'Roboto', fontSize: 14 },
ticks: { beginAtZero: true, fontSize: 12, userCallback: (label, index, labels) => {
if (Math.floor(label) === label && label >= 0) { return label; } } } } ]
}
}
};

Chart.js add border around line chart, and yAxis unit title ([s])

I have problem with chartJS. I cannot add border around chart, yAxis unit title, and yAxis labelString with element. I'm using react with typescript. I can add only string to labelString. You can see what I want do do on screen and on another screen you can see what I actualy have.
Is there any options in chart.js#2.7.1 to add these elements?
First image is my goal. Second is actual.
#edit
This is my chartOptions file. I just pass arguments in function to get these options.
import * as Chart from 'chart.js';
const getOptions = (
beginAtZero: boolean,
tickMax: number,
tickStepValue: number,
titleText: string,
xAxesLabelString: string,
yAxesLabelString: string,
): Chart.ChartOptions => {
const ticks: Chart.LinearTickOptions = {
beginAtZero,
fontColor: '#3C3750',
fontFamily: 'Muli',
fontSize: 10,
fontStyle: 'bold',
max: tickMax,
stepSize: tickStepValue,
};
const options: Chart.ChartOptions = {
legend: {
display: false,
},
maintainAspectRatio: false,
responsive: true,
scales: {
xAxes: [{
display: true,
gridLines: {
display: false,
},
scaleLabel: {
display: true,
fontColor: '#3C3750',
fontFamily: 'Muli',
fontSize: 10,
fontStyle: 'bold',
labelString: xAxesLabelString,
},
ticks,
}],
yAxes: [{
display: true,
gridLines: {
drawBorder: true,
tickMarkLength: 15,
},
scaleLabel: {
display: true,
fontColor: '#3C3750',
fontFamily: 'Muli',
fontSize: 10,
fontStyle: 'bold',
labelString: yAxesLabelString,
},
ticks,
}],
},
title: {
display: true,
text: titleText,
},
tooltips: {
backgroundColor: '#E4677B',
callbacks: {
label: (tooltipItem, data) => {
return 'Time: ' + data.datasets[0].data[tooltipItem.index];
},
title: (tooltipItem, data) => {
return '';
},
},
custom: (tooltip) => {
if (!tooltip) {
return;
}
// disable displaying the color box;
tooltip.displayColors = false;
},
},
};
return {
...options,
};
};
export default getOptions;
public createChart({room, roomState, chartOptions, chartDataset, chartLabels}: ILineChartProps) {
const ctx = this.canvas.getContext('2d');
this.myChart = new Chart(ctx, {
data: {
datasets: chartDataset,
labels: chartLabels,
},
options: chartOptions,
type: 'line',
});
}
Adding one xAxes on top and one yAxes on right both showing nothing will do the job.
scales: {
xAxes: [{
/* Your xAxes options here */
}, {
position: 'top',
ticks: {
display: false
},
gridLines: {
display: false,
drawTicks: false
}
}],
yAxes: [{
/* Your yAxes options here */
}, {
position: 'right',
ticks: {
display: false
},
gridLines: {
display: false,
drawTicks: false
}
}]
}
This is what worked for me.
scales: {
xAxes: [
{
/* Your xAxes options here */
},
{
position: 'top',
ticks: {
display: false
},
gridLines: {
display: true,
drawOnChartArea: false,
drawTicks: false
}
}
],
yAxes: [
{
/* Your yAxes options here */
},
{
position: 'right',
ticks: {
display: false
},
gridLines: {
display: true,
drawOnChartArea: false,
drawTicks: false
}
}
]
}

Categories

Resources