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

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>

Related

Charts.js scales yaxes ticks min max doesnt work

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>

How do you set x and y axis and Title for a line chart using charts.js?

This is using charts.js. This code only makes the line graph but the title, x axis and y axis does not show. I want to add title, and the names for those 2 axis onto the graph. what is wrong and how do you fix it? I also want to make the y axis to start from 0 and up.
async function chartDisplay() {
await getData1();
await getData2();
const ctx = document.getElementById('chart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: xLabels,
datasets: [{
data: ratingDataI,
label: "data1",
borderColor: "#3E95CD",
fill: false
},
{
data: ratingDataA,
label: "data2",
borderColor: "#3E95CD",
fill: false
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart'
},
tooltips: {
mode: 'label',
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
x: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Dates'
}
}],
y: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
});
}
the x and y should not be arrays but objects, also the scaleLabel prop is called title now. For all the changes please read the migration guide (https://www.chartjs.org/docs/master/getting-started/v3-migration.html)
Example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}]
},
options: {
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'yAxis'
}
},
x: {
title: {
display: true,
text: 'xAxis'
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>

How to display final point value in charts.js

I'm using Charts.js library to display a line graph from data which is constantly updated. Is there a way to display only the final point value at all times? I want it to do this to monitor the added values at all times.
javascript code:
var config2 = {
type: 'line',
data: {
labels: 0,
datasets: [{
label: "No selection",
lineTension: 0,
borderColor: "rgba(222, 44, 31)",
pointBackgroundColor: "#fff675",
fill: false,
data: 0,
}
]
},
options: {
responsive: true,
title: {
display: false,
text: 'Chart.js Time Point Data'
},
scales: {
x: {
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
ticks: {
major: {
enabled: true
},
fontStyle: function(context) {
return context.tick && context.tick.major ? 'bold' : undefined;
},
fontColor: function(context) {
return context.tick && context.tick.major ? '#FF0000' : undefined;
}
}
},
y: {
display: true,
scaleLabel: {
display: true,
labelString: 'value'
}
}
}
}
};
Each time, a new value is available, you can simply remove outdated labels and dataset.data values once a certain limit is reached. This can be done using Array.shift(), which removes the first element from an array. Once these array are updated, you need to invoke chart.update().
var maxValues = 4;
setInterval(() => {
chart.data.labels.push(new Date());
chart.data.datasets[0].data.push(Math.floor((Math.random() * 20) + 1));
if (chart.data.labels.length > maxValues) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
}
chart.update();
}, 1000);
For displaying the value on the last added data point, you can use the Plugin Core API. It offers different hooks that may be used for executing custom code. In below runnable code snippet, I use the afterDraw hook to draw text directly on the canvas.
var chart = new Chart('chart', {
type: "line",
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
var iLastValue = chart.data.labels.length - 1;
var lastValue = chart.data.datasets[0].data[iLastValue];
var x = xAxis.getPixelForValue(chart.data.labels[iLastValue]);
var y = yAxis.getPixelForValue(lastValue);
ctx.save();
ctx.textAlign = 'center';
ctx.font = '14px Arial';
ctx.fillStyle = "red";
ctx.fillText('Value: ' + lastValue, x, y - 15);
ctx.restore();
}
}],
responsive: true,
maintainAspectRatio: false,
data: {
labels: [],
datasets: [{
label: "Data",
data: [],
fill: false,
lineTension: 0,
backgroundColor: "white",
borderColor: "red",
}]
},
options: {
layout: {
padding: {
right: 50
}
},
scales: {
xAxes: [{
type: 'time',
ticks: {
source: 'auto'
},
time: {
unit: 'second',
displayFormats: {
second: 'mm:ss'
},
tooltipFormat: 'mm:ss'
},
}],
yAxes: [{
ticks: {
min: 0,
max: 20,
stepSize: 5
}
}]
}
}
});
var maxValues = 4;
setInterval(() => {
chart.data.labels.push(new Date());
chart.data.datasets[0].data.push(Math.floor((Math.random() * 20) + 1));
if (chart.data.labels.length > maxValues) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
}
chart.update();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="chart" height="90"></canvas>

Image drawn by drawImage() function hide when mover hover on bar chart column

I draw a chart using chart js on canvas. Then I draw a image on top of the column of chart. When I load the page It shows properly. But when I hover mouse on chart column, image gone hide.
I have tried with chart js. I have tried with morris js.
let myChart = document.getElementById('myChart').getContext('2d');
// Global Options
Chart.defaults.global.defaultFontFamily = 'Lato';
Chart.defaults.global.defaultFontSize = 18;
Chart.defaults.global.defaultFontColor = '#777';
let massPopChart = new Chart(myChart, {
type: 'bar', // bar, horizontalBar, pie, line, doughnut, radar, polarArea
data: {
labels: ['Boston', 'Worcester', 'Springfield', 'Lowell', 'Cambridge', 'New Bedford'],
datasets: [{
label: 'Population',
data: [
6,2,7,3,4,6
],
backgroundColor: '#1d569e',
borderWidth: 1,
borderColor: '#777',
hoverBorderWidth: 3,
hoverBorderColor: '#000'
}]
},
options: {
title: {
display: true,
text: 'Largest Cities In Massachusetts',
fontSize: 25
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#000'
}
},
layout: {
padding: {
left: 50,right: 0,bottom: 0,top: 0
}
},
tooltips: {
enabled: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
var canvas = document.getElementById('myChart');
var context = canvas.getContext('2d');
var imgPath = 'https://i.imgur.com/t0MRiAf.png';
var imgObj = new Image();
imgObj.src = imgPath;
imgObj.onload = function() {
context.drawImage(imgObj, 0, 0, 100, 100);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<div class="container">
<canvas id="myChart"></canvas>
</div>
I want to show the image on top of column. It will be responsive.

Horizontal spacing in ChartJS Bar Graph

I am using Chart.js plugin.
I want to reduce the horizontal spacing.
Image 1 : I try
Image 2 : I want
JSFiddle Link Here!
HTML Code Here
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<canvas id="myChart" width="800" height="300"></canvas>
CSS Code Here
canvas {
margin:0 auto;
}
JS Code Here
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['April', 'May'],
datasets: [{
label: 'facebook',
borderColor: 'rgba(0,0,0,0)',
backgroundColor: '#3b5998',
data: [179, 201]
}, {
label: 'instagram',
borderColor: 'rgba(255,255,255,0)',
backgroundColor: '#e8361c',
data: [31, 47]
}]
},
options: {
responsive: false,
scales: {
yAxes: [{
display: false,
ticks: {
suggestedMin: 0
},
gridLines: {
display:false
}
}],
xAxes: [{
display:true,
barPercentage: 0.7,
categoryPercentage: 0.3,
gridLines: {
display:false
}
}]
},
legend: {
position:'bottom'
},
animation:false
}
});
I want to reduce the interval between categories. I do not know if there is a corresponding option. Please help me.

Categories

Resources