Chart.js Scatter Chart bounds: 'data' Issue - javascript

I'm currently struggling with building a web frontend with a responsive chart, which should be filled with live data while the user is visiting the application.
My goal was to have the x-axis always scale automatically to perfectly cover the data. Then I found the bounds attribute of Chart.js, which when set to 'data' should do exactly what I want.
As you can see in this example, the whole thing only works well for the first few datasets - from x-values > 5 onwards, the scaling of the x-axis somehow gets messed up.
Did anyone else have this problem before? Did I assign other attributes incorrectly?
Here's my JavaScript code:
var data = [];
var graph = new Chart("chart", {
type: 'scatter',
data: {
datasets: [{
data: data,
pointRadius: 0,
borderWidth: 2,
pointHitRadius: 4,
pointHoverRadius: 6,
tension: 0,
showLine: true,
xAxisID: "xAxis",
yAxisID: "yAxis",
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
animation: false,
plugins: {
legend: {
display: false,
},
},
interaction: {
mode: 'nearest',
intersect: true,
},
scales: {
xAxis: {
type: 'linear',
position: 'bottom',
title: {
display: true,
text: 't (s)',
color: "black",
font: {
size: 15
}
},
ticks: {
color: "black",
callback: (value, index, values) => (index == (values.length - 1)) ? "" : value,
},
bounds: 'data'
},
yAxis: {
type: 'linear',
position: 'left',
ticks: {
color: "black",
maxTicksLimit: 7,
}
}
}
}
});
var x = 0;
setInterval(function() {
var newData = {
x: Math.round(x * 100) / 100,
y: Math.round(x * 100) / 100
};
data.push(newData);
graph.update();
x += 0.1;
}, 100);

Related

Chart js how to move legend to bottom but save legend type as list

Hi!. How could I do as in example image which i pinned? I want to make donut in center and two legends column under the chart.
Here is my code which i write - but it make very ugly legends by default. I want save this legend style but move them to bottom.
I watched many youtube video how to do it but i dont understand how.
var token_allocations_ctx = d("token_allocations_canvas");
var token_allocations_chart = new Chart(token_allocations_ctx, {
type: 'doughnut',
data: {
labels: token_allocations_labels,
datasets: [{
label: 'Allocations',
data: token_allocations_data,
backgroundColor: [
'#8b03f7'
],
borderWidth: 0,
hoverBorderWidth: 0,
borderAlign: 'center',
hoverOffset: 15,
}]
},
options: {
animation: {
animateScale: false
},
cutout: "80%",
borderRadius: 30,
responsive: true,
radius: 100,
layout: {
padding: 18
},
plugins: {
legend: {
position: "right",
align: "right",
labels: {
usePointStyle: true,
boxWidth: 100
}
},
tooltip: {
// displayColors: false,
usePointStyle: true,
boxWidth: 10,
callbacks: {
label: function(context) {
let label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
console.log(context)
label += token_allocations_labels_procent[context.dataIndex]
}
return label;
},
title: function(context) {
return context.label;
},
}
},
},
}
});

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>

How to add a vertical line on the end of the chart.js scatter graph

This is how options for my chart look like
options: {
legend: {
display: false
},
scales: {
xAxes: [
{
type: "time",
gridLines: {
display: false
},
ticks: {
padding: 15
}
}
],
yAxes: [
{
ticks: {
padding: 22,
min: 1,
max: 5,
stepSize: 1
},
position: "left",
gridLines: {
drawTicks: false
}
}
]
}
}
as you can see there is an option
gridLines: {
display: false
},
because of this there is no vertical lines on the chart.
What I want to do is to add only one vertical line on the end of the chart(right side of the chart)
Here is my live example https://codesandbox.io/s/line-chart-with-vanilla-js-and-chartjs-pi9fn?file=/src/index.js
This can be solved as follows:
Define data.labels in the chart configuration. Given your data, this could be done by extracting the x values of of the data objects using Array.map().
const labels = data.map(o => o.x);
Then you need to adapt xAxis.ticks in order to instruct Chart.js that ticks (including grid lines) have to be generated from user given labels (see Tick Source from Chart.js documentation).
ticks: {
source: 'labels'
}
Further you have to change the definition of xAxis.gridLines. Make them displayed again and define lineWidth instead. This should be an array of numbers that specify the stroke width of individual grid lines. Basically all 0 except 1 for the last number.
gridLines: {
lineWidth: labels.map((l, i) => i < labels.length - 1 ? 0 : 1)
}
Please have a look at the runnable code snippet below.
const data = [
{ x: "1-01", y: 1 },
{ x: "1-07", y: 3 },
{ x: "1-14", y: 2 },
{ x: "1-21", y: 4 },
{ x: "1-28", y: 5 },
{ x: "2-04", y: 1 }
];
const labels = data.map(o => o.x);
new Chart('line-chart', {
type: "scatter",
responsive: true,
maintainAspectRatio: false,
data: {
labels: labels,
datasets: [
{
data: data,
label: "A",
showLine: true,
fill: false,
borderWidth: 4,
pointRadius: 5,
tension: 0,
backgroundColor: "#ffffff",
borderColor: "red"
}
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [
{
type: 'time',
unit: 'day',
time: {
parser: 'M-D'
},
gridLines: {
lineWidth: labels.map((l, i) => i < labels.length - 1 ? 0 : 1)
},
ticks: {
source: 'labels',
padding: 15
}
}
],
yAxes: [
{
ticks: {
padding: 22,
min: 1,
max: 5,
stepSize: 1
},
position: "left",
gridLines: {
drawTicks: false
}
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="line-chart" height="90"></canvas>

Chart.js Mouse Over Show Old Chart Data

I was having some problem when trying to redraw chart on canvas using chart.js in Angular. Here is my HTML component:
<div class="form-group">
<select [(ngModel)]="timeMode" id="timeModeInput" class="browser-default custom-select" (change)="onTimeModeChange($event)">
<option value="all" selected>Yearly</option>
<option value="monthly">Monthly</option>
</select>
</div>
<canvas id="expenseTimelineCanvas"></canvas>
Upon dropdown select, I repopulate the chart:
if (chart != null) { chart.destroy(); chart.clear(); }
chart = new Chart(chartName, {
type: "line",
data: {
labels: labels,
datasets: [
{
data: chartData,
borderColor: lineColor,
fill: false,
borderWidth: 1,
borderDash: [10, 10],
pointBackgroundColor: "white",
pointBorderColor: lineColor,
pointRadius: 5
}
]
}
}
});
However, when I mouse over at certain part of the canvas, the old chart will be displayed. Any ideas on how to totally destroy the canvas before replotting on the same DOM element?
Thanks!
this happens because chartjs uses canvas and for redrawing you just have to destroy old drawing from the canvas.
when you make a new chart then you have to destroy the old chart.
but in angular you can also just reload the component to destroy the chart
your method
//this method
initChart(){
//this will generate chart you need
//before generating just destroy the old chart
}
second method
//in html file
<thisIsHTMLTagOfChartComponent *ngIf="showChart">
</thisIsHTMLTagOfChartComponent>
//in typescript
public showChart = false;
//this function will be called everytime you fetch the data from server
getChartData(){
this.showChart = false; //this will remove the component from the page
fetchData(uri)
.then(result => {
//do your stuff here
this.showChart = true // this will load the component in the page again
}
)
i prefer to not destroy your chart just change the value of it for e.g: in your change function just load a new chart definition in your same chart with new config, we have 2 different configs:
config = {
type: 'bar',
data: {
labels: dringlichkeiten.map(x => x.id),
datasets: [
{
label: 'My Bar Chart',
data: dringlichkeiten.map(x => x.value),
backgroundColor: ['red', 'green', 'yellow', 'blue', 'orange']
}
]
},
}
config2 = {
type: 'line',
data: {
datasets: [{
label: 'Höhenlinie',
backgroundColor: "rgba(255, 99, 132,0.4)",
borderColor: "rgb(255, 99, 132)",
fill: true,
data: [
{ x: 1, y: 2 },
{ x: 2500, y: 2.5 },
{ x: 3000, y: 5 },
{ x: 3400, y: 4.75 },
{ x: 3600, y: 4.75 },
{ x: 5200, y: 6 },
{ x: 6000, y: 9 },
{ x: 7100, y: 6 },
],
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Höhenlinie'
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
ticks: {
userCallback: function (tick) {
if (tick >= 1000) {
return (tick / 1000).toString() + 'km';
}
return tick.toString() + 'm';
}
},
scaleLabel: {
labelString: 'Länge',
display: true,
}
}],
yAxes: [{
type: 'linear',
ticks: {
userCallback: function (tick) {
return tick.toString() + 'm';
}
},
scaleLabel: {
labelString: 'Höhe',
display: true
}
}]
}
}
}
chart: Chart ;
in your change function just load a new config:
change(){
this.chart = new Chart('canvas', this.config2)
}
DEMO.

Chart.js stacked bar chart in opposite direction

I am trying to achieve something like this using chart.js. I wanted to show data of male/female according to each age group:
Here is my chart options:
var options = {
layout: {
padding: {
top: 5,
}
},
scales:
{
yAxes: [{
display: true,
barPercentage: 0.4,
ticks: {
fontSize: 12
},
stacked: true,
}],
xAxes: [{
stacked: true,
}]
},
responsive: true,
maintainAspectRatio: false,
legend: {
display: false,
},
animation: {
animateScale: true,
animateRotate: true
},
};
var opt = {
type: "horizontalBar",
data: {
labels: ageGroup,
datasets: [{
label: 'Male',
data: maleData,
backgroundColor: '#2196F3',
hoverBackgroundColor: '#2196F3'
},
{
label: 'Female',
data: femaleData,
backgroundColor: '#E91E63',
hoverBackgroundColor: '#E91E63'
}]
},
options: options
};
I changed the positive in femaleData array into a negative number to achieve the result above:
for (var i = 0; i < femaleData.length; i++) {
femaleData[i] = -Math.abs(femaleData[i]);
}
However, the y-axis at 0 is not centralized as it pushed to the right hand side since left hand side got more data. I not even sure if this is the correct way to set the chart in opposite direction. How can I do this correctly?
as per the requirements mentioned in OP­'s comment section
ꜱʜᴏᴡ ᴘᴏꜱɪᴛɪᴠᴇ ᴠᴀʟᴜᴇꜱ ᴏɴ x-ᴀxɪꜱ
use the following callback function for x-axis ticks :
callback: function(t, i) {
return t < 0 ? Math.abs(t) : t;
}
ꜱʜᴏᴡ ᴘᴏꜱɪᴛɪᴠᴇ ᴠᴀʟᴜᴇ ᴏɴ ᴛᴏᴏʟᴛɪᴘ
use the following callback function for tooltips :
callbacks: {
label: function(t, d) {
var datasetLabel = d.datasets[t.datasetIndex].label;
var xLabel = Math.abs(t.xLabel);
return datasetLabel + ': ' + xLabel;
}
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var ageGroup = ['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80', '80+'];
var maleData = [30, 0, 0, 0, 10, 0, 0, 0, 0];
var femaleData = [0, 0, 0, -20, -50, -20, 0, 0, 0];
var options = {
layout: {
padding: {
top: 5,
}
},
scales: {
yAxes: [{
display: true,
barPercentage: 0.4,
ticks: {
fontSize: 12
},
stacked: true,
}],
xAxes: [{
stacked: true,
ticks: {
callback: function(t, i) {
return t < 0 ? Math.abs(t) : t;
}
}
}]
},
tooltips: {
callbacks: {
label: function(t, d) {
var datasetLabel = d.datasets[t.datasetIndex].label;
var xLabel = Math.abs(t.xLabel);
return datasetLabel + ': ' + xLabel;
}
}
},
responsive: true,
//maintainAspectRatio: false,
legend: {
display: false,
},
animation: {
animateScale: true,
animateRotate: true
},
};
var opt = {
type: "horizontalBar",
data: {
labels: ageGroup,
datasets: [{
label: 'Male',
data: maleData,
backgroundColor: '#2196F3',
hoverBackgroundColor: '#2196F3'
}, {
label: 'Female',
data: femaleData,
backgroundColor: '#E91E63',
hoverBackgroundColor: '#E91E63'
}]
},
options: options
};
new Chart(ctx, opt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

Categories

Resources