Custom alphanumerical values in chart.js? - javascript

I am trying to make a simple horizontal bar chart with Chart.js with some languages ('Spanish', 'English', ...) in the y-axis and its CEFR Level (from A1 to C2) in the x-axis instead of some numerical level (1-10 for example).
Is there a way to have a bar chart without pure numerical values in the x-axis?
That is what I'm getting right now with this code:
var spokenLangChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['Spanish', 'English', 'German'],
datasets: [{
label: 'CEF Level',
labels: ['A1', 'A2', 'B1', 'B2', 'C1', 'C2'],
data: ['C2', 'C1', 'B1'],
backgroundColor: "rgba(255,153,0,0.4)"
}]
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});

Currently, ChartJS does not support directly two axis without numerical values. But you can accomplish this with callbacks as you can see on my example:
var ctx = document.getElementById('chart');
var xLabels = ["A","B","C","D","E","F","G","H","I","J","K"]; //Put here your x labels
var spokenLangChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['Spanish', 'English', 'German'], //Put here your x labels
datasets: [{
label: 'CEF Level',
labels: ['A1', 'A2', 'B1', 'B2', 'C1', 'C2'],
data: ['C2', 'C1', 'B1'],
backgroundColor: "rgba(255,153,0,0.4)"
}]
},
options: {
scales: {
xAxes: [{
ticks: {
//Returns the x labels
callback: function(value, index, values) {
return xLabels[index];
}
},
}]
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="chart" width="200" height="100"></canvas>
Or look at JSFiddle.
I hope it helps you.

So thanks to Julian Schmuckli I was able to fix this. Since it wasn't entirely solved I'm going to post my own answer so I can share the result.
var ctx = document.getElementById('spokenLangChart').getContext('2d');
var xLabels = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2'];
var spokenLangChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['Spanish', 'English', 'German'], //Put here your x labels
datasets: [{
label: 'CEF Level',
data: [5, 4, 3],
backgroundColor: "rgba(255,153,0,0.4)"
}]
},
options: {
legend: {
position: 'bottom'
},
title: {
display: true,
text: 'Spoken Languages'
},
scales: {
xAxes: [{
ticks: {
beginAtZero: true,
//Returns the x labels
callback: function (value, index, values) {
return xLabels[index];
}
}
}]
}
}
});
It's very important that you put beginAtZero: true, otherwise it will put your lowest value as zero and as I hadn't numerical values it was a bit difficult to spot the error.
Here's the final result:

Related

Side by side dual bar chart with Chart.js 2

Is it possible to do this with Chart.js (v2)? I know how to do multiple axes charts, but all of the examples I've seen so far are limited to overlapped (eg:line+bar) or stacked bar charts that are on the same plane.
This is a close example of what I want but not quite right
var canvas = document.getElementById('chart');
new Chart(canvas, {
type: 'bar',
data: {
labels: ['Target', 'Actual'],
datasets: [{
label: 'A',
yAxisID: 'A',
data: [1400,0]
}, {
label: 'B',
yAxisID: 'B',
data: [0,0.83]
}]
},
options: {
scales: {
yAxes: [{
id: 'A',
type: 'linear',
position: 'left',
}, {
id: 'B',
type: 'linear',
position: 'right',
ticks: {
max: 1,
min: 0
}
}]
}
}
});

chartjs - multi axis line chart - cannot read property 'min' of undefined

When running the below code without the scales and yAxisID values, it renders a 2 line chart with both lines on the same axis.
UPDATE: When only removing the yAxisID values from the code it runs as before without errors - although still with only a single y axis.
When adding these elements in order to get a split axis, it returns the js error cannot read property 'min' of undefined and the canvas is blank.
Not sure if his should make a difference, but data is a json object returned through an ajax request by way of a vue.js method.
Here is an example of how the data.sales variable looks in the browser console:
sales: (187) [0, 0, 43.2874, 10.276, ..., 23.834]
var ctx = document.getElementById("chart_canvas").getContext('2d')
var basic_line = new Chart(ctx, {
type: 'line',
data: {
labels: data.labels,
datasets: [{
label: 'Price',
yAxisID: 'B',
fill: false,
borderColor: ["#668cff"],
data: data.price
}, {
label: 'Sales',
yAxisID: 'A',
fill: false,
borderColor: ["grey"],
data: data.sales
}],
options: {
scales: {
yAxes: [{
id: 'A',
position: 'left',
type: 'linear'
}, {
id: 'B',
position: 'right',
type: 'linear'
}]
},
responsive: true,
maintainAspectRatio: false
}
}
})
The issue is merely occurring due to the fact that, you have placed the options object/property, inside the data property, while it should be outside.
Here is the revised version of your code :
var ctx = document.getElementById("chart_canvas").getContext('2d')
var basic_line = new Chart(ctx, {
type: 'line',
data: {
labels: data.labels,
datasets: [{
label: 'Price',
yAxisID: 'B',
fill: false,
borderColor: ["#668cff"],
data: data.price
}, {
label: 'Sales',
yAxisID: 'A',
fill: false,
borderColor: ["grey"],
data: data.sales
}]
},
options: {
scales: {
yAxes: [{
id: 'A',
position: 'left',
type: 'linear'
}, {
id: 'B',
position: 'right',
type: 'linear'
}]
},
responsive: true,
maintainAspectRatio: false
}
});

How to feed hour and minute data into chartJS

I'm trying to make a line chart using Chart.js. My data is of the form:
var result = [{x:"18:00",y:"230"},{x:"19:00",y:"232"},{x:"20:00",y:"236"},{x:"22:00",y:"228"}];
Where x represents the time with hours and minutes. I fed the data like this
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","21:00","22:00","23:00","24:00"],
datasets: [{
label: 'Voltage Fluctuation',
data: result,
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
position: 'bottom',
unit: 'minute',
time: {
displayFormats: {
hour: 'HH:mm'
}
}
}],
},
}
});
And I'm getting an empty chart. Where am I going wrong? I feel I'm doing something wrong with my labels since they don't show up on the chart but I don't understand how. Is there any way I can feed datalabels with momentjs?
You cannot just pass the result array to data, as it isn't in correct format. data property expects an array of numbers. So, you need to parse the labels (using moment.js) and data from result array before using them for the chart.
Here is how labels and data should be parsed from the result array and fed to the chart :
var result = [{ x: "18:00", y: "230" }, { x: "19:00", y: "232" }, { x: "20:00", y: "236" }, { x: "22:00", y: "228" }];
// parse labels and data
var labels = result.map(e => moment(e.x, 'HH:mm'));
var data = result.map(e => +e.y);
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Voltage Fluctuation',
data: data,
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'hour',
displayFormats: {
hour: 'HH:mm'
}
}
}]
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>

chartjs: How to remove specific label

I have a Bar Chart with these data and options:
var data = {
labels: periodnames,
datasets: [
{
yAxisID: "bar-stacked",
data: rcash,
backgroundColor: "#FFCE56",
label:""
},
{
yAxisID:"bar-stacked",
data: pcash,
backgroundColor: "#FFCE56",
label: "cash"
}
]
};
var options = {
animation: {
animateScale: true
},
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [
{
display:false,
id: "line-axis",
},
{
id: "bar-stacked",
stacked: true,
}
]
}
}
finactivityGraphChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
The result chart is this:
My problem is that I don't want to show the first dataset's label. If I don't define it, it shows the yellow box with the value "undefine" next to it. I suppose that I must modify the Chart.js file. Any suggestions?
This could be achieved, using the filter function of legend­*'s* label.
see Legend Label Configuration
In short, add the following in your chart options ...
legend: {
labels: {
filter: function(label) {
if (label.text === 'cash') return true;
}
}
},
ᴅᴇᴍᴏ
var ctx = document.querySelector('#c').getContext('2d');
var data = {
labels: ['Jan', 'Feb', 'Mar'],
datasets: [{
yAxisID: "bar-stacked",
data: [1, 2, 3],
backgroundColor: "#FFCE56",
label: "gold"
}, {
yAxisID: "bar-stacked",
data: [-1, -2, -3],
backgroundColor: "#FFCE56",
label: "cash"
}]
};
var options = {
legend: {
labels: {
filter: function(label) {
if (label.text === 'cash') return true; //only show when the label is cash
}
}
},
animation: {
animateScale: true
},
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
display: false,
id: "line-axis",
}, {
id: "bar-stacked",
stacked: true,
}]
}
}
finactivityGraphChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
<canvas id="c"></canvas>

How To Format Scale Numbers in Chart.js v2

First of all, I apologize if my question is a slightly the same as others question. I searched for a solution and found 3 similar questions, yet none of them worked in my case, because the examples I found use Chart.js v1.
I saw a sample using a function placed in scaleLabel to format the numbers just like this:
var options = {
animation: false,
scaleLabel: function(label){
return '$' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
};
The above code, however, doesn't work anymore in the new Chart.js v2.
How can I format the scale numbers in Chart.js v2?
Here is my code: https://jsfiddle.net/2n7xc7j7/
When adding option configurations, you need to make sure you nest the settings in the right sections. You can format the scale numbers by adding a callback function to the yAxes ticks configuration section:
options = {
scales: {
yAxes: [{
ticks: {
callback: function(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
}
}]
}
};
JSFiddle Demo: https://jsfiddle.net/2n7xc7j7/1/
In V3 the locale property has been added. This makes it so all the numbers on the scales an tooltips get formatted correctly automatically in the numberformat of that country code:
// Element
const ctx = document.getElementById("myChart")
// Data
const data = {
labels: ['First', 'Second', 'Third', 'Fourth'],
datasets: [{
label: 'Sample',
data: [2982, 1039, 3200, 2300],
backgroundColor: "rgba(90, 150, 220, 0.85)",
borderColor: "rgba(70, 120, 180, 1)",
borderWidth: 2
}],
}
// Options
const options = {
locale: 'en-US'
};
const chart_trans_hari = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
I did this:
http://profwtelles.ddns.net/grafico2.html
var canvas = document.getElementById('chart');
new Chart(canvas, {
type: 'line',
data: {
labels: ['1', '2', '3', '4', '5'],
datasets: [{
label: 'A',
yAxisID: 'A',
data: [100, 96, 84, 76, 69]
}, {
label: 'B',
yAxisID: 'B',
data: [1, 1, 1, 1, 0]
}]
},
options: {
scales: {
yAxes: [{
id: 'A',
type: 'linear',
position: 'left',
}, {
id: 'B',
type: 'linear',
position: 'right',
ticks: {
max: 1,
min: 0
}
}]
}
}
});
I hope to help you.
Best Regards

Categories