Charts.js scales yaxes ticks min max doesnt work - javascript

I have an HTML page with a charts.js chart that works. I'm trying to set the minimum and maximum values of the chart, but I can't set the minimum and maximum values. I searched different posts but they all say the same, and I'm pretty sure I'm already doing that...
> scales: {
> yAxes: [{
> ticks: {
> min: -100,
> max: 100
> }
> }]
> }
I just cant figure out what's wrong.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.0.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0-rc/dist/chartjs-plugin-datalabels.min.js"></script>
<title>daily</title>
</head>
<body>
<canvas class='temp_chart' id='temp_chart'>
</body>
<script>
function square_data(chart){
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FFA500";
ctx.rect(145, 70, 15, 15);
ctx.fill()
ctx.fillStyle = "#fff";
ctx.fillText(chart.dataset.data[chart.dataIndex], 147,82, 10);
ctx.stroke();
return c
}
const time_of_day = ['Morning', 'Day', 'Evening', 'Night']
var temperatures = [15, 18, 4, -6]
var ctx = document.getElementById('temp_chart').getContext('2d')
window.chart = new Chart(ctx, {
type: 'line',
data: {
labels: time_of_day,
datasets: [{
fill:false,
label: 'Cantidad Estudiantes',
data: temperatures,
borderColor: [
'rgba(0, 0, 0, 1)',
],
borderWidth: 3
}]
},
options: {
plugins: {
legend: {
display: false,
},
datalabels: {
anchor: 'start',
align: '-45',
clamp: true,
color: "orange",
}
},
elements:{
"point":{"pointStyle":square_data},
}
},
scales: {
yAxes: [{
ticks: {
min: -100,
max: 100
}
}]
}
});
</script>

That is because you are using v2 syntax with v3, for all changes please read the migration guide and you defined the scale config outside of the options object.
In v3 all scales are an object where the key of the object is the ID of the scale
Also for the datalabels plugin to work you need to register it, see first line in the script block.
Last thing dont include 2 major versions of a lib, high chance of giving errors
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.0.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0"></script>
<title>daily</title>
</head>
<body>
<canvas class='temp_chart' id='temp_chart'>
</body>
<script>
Chart.register(ChartDataLabels); // Added this line
function square_data(chart) {
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FFA500";
ctx.rect(145, 70, 15, 15);
ctx.fill()
ctx.fillStyle = "#fff";
ctx.fillText(chart.dataset.data[chart.dataIndex], 147, 82, 10);
ctx.stroke();
return c
}
const time_of_day = ['Morning', 'Day', 'Evening', 'Night']
var temperatures = [15, 18, 4, -6]
var ctx = document.getElementById('temp_chart').getContext('2d')
window.chart = new Chart(ctx, {
type: 'line',
data: {
labels: time_of_day,
datasets: [{
fill: false,
label: 'Cantidad Estudiantes',
data: temperatures,
borderColor: [
'rgba(0, 0, 0, 1)',
],
borderWidth: 3
}]
},
options: {
// Changed this block
scales: {
y: {
min: -100,
max: 100,
}
},
plugins: {
legend: {
display: false,
},
datalabels: {
anchor: 'start',
align: '-45',
clamp: true,
color: "orange",
}
},
elements: {
"point": {
"pointStyle": square_data
},
}
},
});
</script>

Related

Trendline plugin brakes it all

I have a simple linear chart on my page thanks to chart.js library and it is working fine. Wanted to add a trendline to it. Im using both library and plugin directly in my html file.
<script src="https://cdn.jsdelivr.net/npm/chart.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-trendline" type="text/javascript"></script>
But Im getting error Uncaught TypeError: Failed to execute 'createLinearGradient' on 'CanvasRenderingContext2D': The provided double value is non-finite.
I think, problem is somwhere with dataset. It is working as intended without trendline, but trendline breaks it.
HTML file contains:
<script src="js/progress.js" type="text/javascript"></script>
<input type="text" id="progress" name="progress" placeholder="0"
oninput="progress.validateValues()">
<canvas id="myChart"></canvas>
<script src="js/myChart.js" type="text/javascript"></script>
myChart.js file:
const ctx = document.getElementById('myChart');
const data = {
datasets: [{
label: 'Progress',
data: [],
fill: false,
borderColor: 'rgb(222, 11, 11)',
trendlineLinear: {
colorMin: 'red',
colorMax: 'green',
lineStyle: 'solid',
width: 2,
projection: true,
},
}],
};
chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
x: {
type: 'linear',
min: 0,
suggestedMax: 6,
grid: {
display: true,
color: 'rgb(60, 80, 130)',
},
ticks: {
display: true,
color: 'rgb(120, 160, 255)',
backdropColor: 'rgba(0, 0, 0, 0)',
},
},
y: {
type: 'linear',
suggestedMin: 2,
suggestedMax: 8,
grid: {
display: true,
color: 'rgb(60, 80, 130)',
},
ticks: {
display: true,
color: 'rgb(120, 160, 255)',
backdropColor: 'rgba(0, 0, 0, 0)',
},
}
},
plugins: {
},
},
});
function pushNewData(chart, newData) {
chart.data.datasets.forEach((dataset) => {
dataset.data = newData;
});
chart.update();
};
and progress.js file:
const progress = {
xyDataSet: [],
validateValues: function () {
this.readValues();
pushNewData(chart, this.xyDataSet);
},
readValues: function () {
let arrayValues = [];
arrayValues = document.getElementById("progress").value.replace(/\s+/g, ' ').trim().split(' ').filter(function (element) {
return element >= 0 && element < 19;
});
for (let i = 0; i < arrayValues.length; i++) {
this.xyDataSet[i] = { x: i, y: arrayValues[i] }
};
},
};
In normal way user pass string of values with spaces between like 0 1 1 0 2 1 3 0 2 3 1. Im validating/clearing/parsing that string to array with coordinates newData = [{x: 0, y: 0},{x: 1, y: 1},{x: 2, y: 1},{x: 3, y: 0},{x: 4, y: 2}, etc] and updating chart.
Without trendline it works perfect. With trendline plugin - all gone.
Thank you for any tips!

Chart.js Line chart legend label font size doesn't work

I am using Chart.js and try to make line chart.
I want to make my chart legend label (Tom and Jim) font size more bigger.
I tried like this;
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>My Chart</title>
</head>
<body>
<canvas id="my_chart">
Canvas not supported...
</canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script>
(function() {
'use strict';
var type = 'line';
var data = {
labels: [2019, 2020, 2021, 2022],
datasets: [{
label: 'Tom',
data: [120, 350, 250, 210],
borderColor: 'red',
borderWidth: 5,
fill: false,
lineTension: 0,
pointStyle: 'rect'
}, {
label: 'Jim',
data: [180, 200, 300, 500],
borderColor: 'blue',
borderWidth: 5,
fill: false,
backgroundColor: 'rgba(0, 0, 255, 0.3)',
lineTension: 0,
pointStyle: 'triangle'
}]
};
var options = {
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 400
}
}]
},
legend: {
position: 'right',
fontSize: 100,
}
};
var ctx = document.getElementById('my_chart').getContext('2d');
var myChart = new Chart(ctx, {
type: type,
data: data,
options: options
});
})();
</script>
</body>
</html>
But It doesn't work. What should I do?
Cf. Chart.js Radar chart legend label font size doesn't work
labels is needed!
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>My Chart</title>
</head>
<body>
<canvas id="my_chart">
Canvas not supported...
</canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script>
(function() {
'use strict';
var type = 'line';
var data = {
labels: [2019, 2020, 2021, 2022],
datasets: [{
label: 'Tom',
data: [120, 350, 250, 210],
borderColor: 'red',
borderWidth: 5,
fill: false,
lineTension: 0,
pointStyle: 'rect'
}, {
label: 'Jim',
data: [180, 200, 300, 500],
borderColor: 'blue',
borderWidth: 5,
fill: false,
backgroundColor: 'rgba(0, 0, 255, 0.3)',
lineTension: 0,
pointStyle: 'triangle'
}]
};
var options = {
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 400
}
}]
},
legend: {
position: 'right',
labels: {
fontSize: 100,
}
}
};
var ctx = document.getElementById('my_chart').getContext('2d');
var myChart = new Chart(ctx, {
type: type,
data: data,
options: options
});
})();
</script>
</body>
</html>

Hover text of canvas in other div

I want to put text beside the canvas doughnut. This text is based on the hover information of each slide, but instead of appear on the top pf the image i want it to be next to it. (2 images as example)
https://jsfiddle.net/jak2e4zr/
HTML
<canvas id="myChart" ></canvas>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
JS
var ctx = document.getElementById("myChart");
var data = {
labels: ['Residential', 'Non-Residential', 'Utility'],
datasets: [
{
data: [19, 26, 55],
weight: 2,
spacing : 5,
borderWidth : 0,
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
circumference: 180,
rotation: -180,
plugins: {
legend: {
display: false
},
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0)',
borderColor: 'rgba(0, 0, 0, 0)',
displayColors: false,
titleAlign: 'center',
xAling: 'center'
}
},
hoverOffset: 15,
}
}); `
Image 1
Image 2
THANKS
The chart.js tooltip object accepts an additional property called position which, well, affects the position of the tooltip. By default it only accepts two strings for setting the mode being either "average" or "nearest". Luckily you're able to define your own mode by extending the Chart.Tooltip.positioners object.
As you want your tooltip to be somewhere in the middle, we can make something like this:
Chart.Tooltip.positioners.middle = function(elements, eventPosition) {
const chart = this._chart;
return {
x: chart.chartArea.width/2,
y: chart.chartArea.height/2
};
}
...so simply querying the chart's current dimensions and take the half of it. This mode can then be used by it's name "middle".
Here's a complete example:
var ctx = document.getElementById("myChart");
Chart.Tooltip.positioners.middle = function(elements, eventPosition) {
const chart = this._chart;
return {
x: chart.chartArea.width / 2,
y: chart.chartArea.height / 2
};
}
var data = {
labels: ['Residential', 'Non-Residential', 'Utility'],
datasets: [{
data: [19, 26, 55],
weight: 2,
spacing: 5,
borderWidth: 0,
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
responsive: false,
circumference: 180,
rotation: -180,
plugins: {
legend: {
display: false
},
tooltip: {
position: 'middle',
backgroundColor: '#ff0000',
titleColor: '#000000',
displayColors: false,
titleAlign: 'center',
xAlign: 'left'
}
},
hoverOffset: 15,
}
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>

How to show values on top of bars in a PDF using chart.js and chartjs-node-canvas?

I need to show the values on the top of bars using chartjs-node-canvas to create a PDF in Node
I have been able to recreate what I am looking in HTML but the plugin has the limitation of not accepting the "animation" property, for this reason I am looking to know if there is another way to do it in Node without the need for another external plugin. This is my current code
var ctx = document.getElementById("myChart");
var chart = new Chart(ctx, {
type: "bar",
data: {
labels: ["a", "b", "c", "d", "e", "f"],
datasets: [
{
type: "bar",
backgroundColor: "blue",
borderColor: "blue",
borderWidth: 1,
label: "promedio",
order: 1,
data: [60, 49, 72, 90, 100, 60]
},
{
type: "bar",
backgroundColor: "orange",
borderColor: "orange",
borderWidth: 1,
label: "promedio",
order: 1,
data: [40, 5, 20, 30, 10, 6]
},
{
type: "line",
label: "casos",
data: [25, 13, 30, 35, 25, 40],
lineTension: 0,
backgroundColor: "red",
borderColor: "red",
order: 0,
fill: false
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
animation: {
duration: 1,
onComplete: function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(16, 20, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 2);
});
});
}
},
legend: {
display: false
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<body>
<canvas id="myChart" width="400" height="200"></canvas>
</body>
Short answer is no, you either have to implement your own external inline plugin or use the datalabels plugin (https://chartjs-plugin-datalabels.netlify.app/samples/charts/bar.html) since there is no build in way to achieve this

First point on scatter plot on JavaScript chart.js not showing

I created a scatter plot, this is the code below. The point at (0,0) does not show on the chart (actually it happens as long as x=0, y can be anything). If I hover on that point, the tooltip does show. Also when I set a title in the options, the title does not show up on the page.
Also how can I put a label on the x and y axis?
Does anyone know what I am doing wrong?
Thanks
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
</head>
<body>
<script>
var canvas = document.createElement('canvas');
canvas.width = 400;
canvas.height = 400;
document.body.appendChild(canvas);
var coordinates = [
{x:0,y:0}, {x:5,y:5}, {x:15,y:15}, {x:20,y:20}, {x:25,y:25}
];
var d1 = coordinates.slice(0,3);
var d2 = coordinates.slice(3,coordinates.length);
var data = {
datasets: [
{
label: "Most Relavant",
borderColor: 'red',
backgroundColor : 'rgba(255,0,0,0.5)',
data: d1
},
{
label: "Others",
borderColor: 'blue',
backgroundColor : 'rgba(0,0,255,0.5)',
data: d2
}
]
};
new Chart(canvas, {
type: 'scatter',
data: data,
title:{
display:true,
text:'Chart.js Line Chart'
},
options: {
responsive : false,
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
}
});
</script>
</body>
</html>
I am on chrome 61 and 62. See screenshot:
Using .01 value instead of 0 is a funky work around. Also have included the parts to label X and Y axis. I'm on Firefox and all looks fine
EDIT: Included the negative start axis values
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
</head>
<body>
<script>
var canvas = document.createElement('canvas');
canvas.width = 400;
canvas.height = 400;
document.body.appendChild(canvas);
var coordinates = [
{x:0,y:0}, {x:5,y:5}, {x:15,y:15}, {x:20,y:20}, {x:25,y:25}
];
var d1 = coordinates.slice(0,3);
var d2 = coordinates.slice(3,coordinates.length);
var data = {
datasets: [
{
label: "Most Relavant",
borderColor: 'red',
backgroundColor : 'rgba(255,0,0,0.5)',
data: d1
},
{
label: "Others",
borderColor: 'blue',
backgroundColor : 'rgba(0,0,255,0.5)',
data: d2
}
]
};
new Chart(canvas, {
type: 'scatter',
data: data,
title:{
display:true,
text:'Chart.js Line Chart'
},
options: {
responsive : false,
scales: {
xAxes: [{
ticks: {
min: -2,
stepSize: 5
},
type: 'linear',
position: 'bottom',
scaleLabel: {
display: true,
labelString: 'X axis label'
}
}],
yAxes: [{
ticks: {
min: -2,
stepSize: 5
},
scaleLabel: {
display: true,
labelString: 'Y axis label'
}
}]
}
}
});
</script>
</body>

Categories

Resources