Chartjs real time graph x axis movement - javascript

I want to display a chart with Chartjs which displays real time data and slowly scrolls along the x axis, I have tried it here with js fiddle and it just jumps like crazy up and down: https://jsfiddle.net/rsnufpq7/
The graph should just move to the left side with the old points out of view without this animation like in the second example here: https://bost.ocks.org/mike/path/
var canvas = document.getElementById('myChart');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
lineTension: 0.0,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 5,
pointHitRadius: 10,
data: [65, 59, 80, 0, 56, 55, 40],
}
]
};
var zero = 7;
function adddata(){
var value = Math.floor((Math.random() * 10) + 1);;
myLineChart.data.labels.push(zero);
myLineChart.data.labels.splice(0, 1);
myLineChart.data.datasets[0].data.splice(0, 1);
myLineChart.data.datasets[0].data.push(value);
myLineChart.update();
zero++;
}
setInterval(function(){
adddata();
},1000);
var option = {
showLines: true
};
var myLineChart = Chart.Line(canvas,{
data:data,
options:option
});

Your code works as expected, only thing that you are missing is your y axis does not have range defined and it is being dynamically adjusted.
In order to achieve this I have extended your options to look like this.
var option = {
showLines: true,
scales: {
yAxes: [{
display: true,
ticks: {
beginAtZero:true,
min: 0,
max: 100
}
}]
}
};
I have defined min and max value for y axis and it is not jumping anymore.
Here is a working fiddle

Related

Sum of results filtered by month in a chart [LARAVEL]

I am currently trying to do a chart with chart.js, and I would like to get the total number of sales over a year in 1 month increments. I'm currently wondering how to break down the number of sales I make every month knowing that I have the "created_at" column for each order. I know how to do the total for each month with a foreach loop, but to cut out the sales and put the total in a table, I don't see how I could do it.
This is what my table looks like:
This is what my chart looks like:
moment().locale('fr');
var canvas = document.getElementById("bellegaiaChart");
var ctx = canvas.getContext('2d');
// Global Options:
Chart.defaults.global.defaultFontColor = 'black';
Chart.defaults.global.defaultFontSize = 16;
var data = {
labels: ["Jan", "Fev", "Mar", "Avr", "Mai", "Juin", "Jui", "AoĆ»", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "Ventes",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(225,0,0,0.4)",
borderColor: "red", // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "black",
pointBackgroundColor: "white",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "brown",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data: [65, 59, 80, 81, 56, 110, 40 ,60,55,30,78],
spanGaps: false,
}, {
label: "Nouveaux Clients",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(167,105,0,0.4)",
borderColor: "rgb(167, 105, 0)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "white",
pointBackgroundColor: "black",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "brown",
pointHoverBorderColor: "yellow",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: false
data: [10, 20, 60, 95, 64, 78, 90,70,40,70,89, 73],
spanGaps: false,
}
]
};
// Notice the scaleLabel at the same level as Ticks
var options = {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
},
scaleLabel: {
display: true,
labelString: 'Moola',
fontSize: 20
}
}]
}
};
// Chart declaration:
var myBarChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
This chart is currently integrated in my blade view.
The goal would be to have a table containing all the sales totals per month (so 12 entries in the table) in order to be able to specify it in the data of my chart.

Chart.JS Multiline Chart with unknown numbers of Lines from JSON

I try do to a Multi - Linechart with chart.js. I have a json dataset from a database. The number of dataset can be different. Here is a example (x can be more) with JSON Data.
[{"name":"name1","jan":4067.5,"feb":1647,
"mrz":1375,"apr":10191,"mai":0,"jun":28679,"jul":59502},
{"name":"name2","jan":47548,"feb":63280.5,
"mrz":51640.26,"apr":75029,"mai":41137,"jun":89114.26,"jul":77332},
{"name":"name3","jan":38099,"feb":55023.5,
"mrz":62668,"apr":39482,"mai":44193.3,"jun":52826.5,"jul":77072},
{"name":"namex","jan":34930.5,"feb":36831.5,
"mrz":24391,"apr":35051,"mai":38038,"jun":12700,"jul":51080}]
I have abbreviated the example, in reality it is until December.
I try to do a chart with a line for every name. The X-axis should be the months of January to December and the Y-axis sales.
34/5000
From what I understand, your dataset will get dynamically updated.
You can just change your dataset then call the update() function.
For example:
First initialize your chart with all the data using:
var canvas = document.getElementById("barChart");
var ctx = canvas.getContext('2d');
var data = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "name 1",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(225,0,0,0.4)",
borderColor: "red",
borderCapStyle: 'square',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "black",
pointBackgroundColor: "white",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "brown",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40, ,60,55,30,78]
}, {
label: "name 2",
fill: true,
lineTension: 0.1,
backgroundColor: "rgba(167,105,0,0.4)",
borderColor: "rgb(167, 105, 0)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "white",
pointBackgroundColor: "black",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "brown",
pointHoverBorderColor: "yellow",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
data: [10, 20, 60, 95, 64, 78, 90,,70,40,70,89]
}
]
};
var options = {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
},
scaleLabel: {
display: true,
labelString: 'Moola',
fontSize: 20
}
}]
}
};
// Chart declaration:
var myBarChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
Then if you later want to update your data, you can just:
myBarChart.data.datasets = [{
label: "name 3",
fill: true,
lineTension: 0.1,
backgroundColor: "rgba(167,105,0,0.4)",
borderColor: "rgb(167, 105, 0)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "white",
pointBackgroundColor: "black",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "brown",
pointHoverBorderColor: "yellow",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
data: [10, 20, 60, 95, 64, 78, 90,,70,40,70,89]
},
...............
];
myBarChart.update();
Also, you will need to format your data in a way that can be used with the charts.
Format your data so that you can create a proper dataset.

how to show multiple values in point hover using chart.js

I want to know that if it is possible to show more values on point hover in chart.js.
Have a look in this fiddle.
This is a smiple graph example taken from the chart.js site. If i hover a point it shows the dataset value.
How can i show other value. like along this array.
[65, 59, 80, 81, 56, 55, 40]
if i want to show this array values
[1, 2, 3, 4, 5, 6, 7]. Like i want to show numbering. This is just an example actually i want to show more two values but not want to plot it on the graph only showed in the pointhover. Like on 65 it tells that it is 1th value.
Any kind of help would be much appreciated.
Yes it is possible, please use tooltips option as below
var ctx = document.getElementById('chart1').getContext("2d");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40],
spanGaps: false,
}
]
};
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: 'anything',
fontSize: 18,
fontColor: "#111"
},
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItems, data) {
var multistringText = [tooltipItems.yLabel];
multistringText.push('Another Item');
multistringText.push(tooltipItems.index+1);
multistringText.push('One more Item');
return multistringText;
}
}
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
},
scales:{
yAxes:[{
ticks:{
min:0
}
}]
}
};
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
<canvas id="chart1"></canvas>
If you want to show data below the existing item in the tooltips you can use the 3 different tooltip footer callbacks. Just define what you want to show as arrays outside of the scope of chart.js and reference it using an index.
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
beforeFooter: function(tooltipItems, data) {
return 'Point #: ' + footerLine1[tooltipItems[0].index];
},
footer: function(tooltipItems, data) {
return 'Other Data: ' + footerLine2[tooltipItems[0].index];
}
}
},
Keep in mind that you only have 3 lines to work with (e.g. 3 footer callbacks)
See the example here.
tooltips: {
mode: 'index'
}
add this to options

drawing line chart with chartjs

I'm trying to draw a line chart with chartjs, but i can't get it working - keep getting 't is undefined' error.
here is my fiddle example: http://jsfiddle.net/6bjy9nxh/344/
can anyone figure out what im doing wrong here?
chartjs: http://www.chartjs.org/docs/#line-chart-example-usage
cdn: https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js
html
<canvas id="myChart" width="500" height="350"></canvas>
javascript
var ctx = document.getElementById("myChart");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40],
}
]
};
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
});
You are including version 1, you need version 2 for Chart.js
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js
http://jsfiddle.net/x55sgzgf/

how to programmatically make a line chart point active/highlighted

I'm using chart.js 2.0 beta2 and have several line charts on a page and a slider. I'd like to highlight the data point on each line chart that matches the slider position (they all have the same number of points). I can't figure out how to easily make a point active in the code. Thanks for any tips.
SOLUTION FOR 2.0 BETA
Extend the chart controller of your choice, and fire off a simulated click event to show the tooltip. Here is some code that works for 2.0 (here is a fiddle):
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
backgroundColor: "rgba(220,220,220,0.2)",
borderColor: "rgba(220,220,220,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(220,220,220,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
tension: 0.1,
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "My Second dataset",
fill: true,
backgroundColor: "rgba(220,220,220,0.2)",
borderColor: "rgba(220,220,220,1)",
pointBorderColor: "rgba(220,220,220,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var options = {
responsive: false
};
Chart.helpers.extend(Chart.controllers.line.prototype, {
fireSliderEvent: function(point, canvas, boundingRect){
var mouseX = Math.round((boundingRect.left + point._view.x) / (boundingRect.right - boundingRect.left) * canvas.width / this.chart.chart.currentDevicePixelRatio);
var mouseY = Math.round((boundingRect.top + point._view.y) / (boundingRect.bottom - boundingRect.top) * canvas.height / this.chart.chart.currentDevicePixelRatio);
var oEvent = document.createEvent('MouseEvents');
oEvent.initMouseEvent('click', true, true, document.defaultView,
0, mouseX, mouseY, mouseX, mouseY,
false, false, false, false, 0, canvas);
canvas.dispatchEvent(oEvent);
},
highlightPoints: function(point){
var canvas = this.chart.chart.canvas;
var boundingRect = canvas.getBoundingClientRect();
var points = this.getDataset().metaData;
this.fireSliderEvent(points[point], canvas, boundingRect);
}
});
var ctx = $("#canvas");
var myLine = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var highlight = function(dataset, point){
myLine.data.datasets[dataset].controller.highlightPoints(point);
}
$("#slider").slider({
max: myLine.data.datasets[0].data.length-1,
slide: function( event, ui ) { highlight(0, ui.value); }
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0-beta/Chart.js"></script>
<div id="slider" style="width: 500px;"></div>
<canvas id="canvas" height="300" width="500"></canvas>
SOLUTION FOR 1.x
You should extend the chart type and add your own method to select the point. Here is some code that will show the tooltip for each point depending on slider position:
var lineChartData = {
"datasets": [{
"data": [
"85",
"87",
"70",
"80",
"78",
"69",
"150",
"93",
"59",
"88"],
"pointStrokeColor": "#fff",
"fillColor": "rgba(220,220,220,0.5)",
"pointColor": "rgba(220,220,220,1)",
"strokeColor": "rgba(220,220,220,1)"
}],
"labels": [
"2013-01-01",
"2013-01-04",
"2013-01-15",
"2013-02-03",
"2013-03-25",
"2013-04-03",
"2013-04-14",
"2013-05-27",
"2013-05-27",
"2013-08-03"],
};
var options = {showTooltips: false};
Chart.types.Line.extend({
name: "LineAlt",
highlightPoints: function(datasetIndex, pointIndexArray){
var activePoints = [];
var points = this.datasets[datasetIndex].points;
for(i in pointIndexArray){
if(points[pointIndexArray[i]]){
activePoints.push(points[pointIndexArray[i]]);
}
}
this.showTooltip(activePoints);
}
});
var myLine = new Chart(document.getElementById("canvas").getContext("2d")).LineAlt(lineChartData, options);
var highlight = function(index){
myLine.highlightPoints(0, [index]);
}
$("#slider").slider({
max: lineChartData.datasets[0].data.length-1,
slide: function( event, ui ) { highlight(ui.value); },
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div id="slider" style="width: 500px;"></div>
<canvas id="canvas" height="300" width="500"></canvas>
First BIG THANKS to JstnPwll for amazing answer that helped me a lot!
The ChartJS API has changed a lot and 2.0 BETA does not work
I needed this in ReactJS and the complexity of "extend" coordinator
was beyond my competence
This simpler works for Chart.JS 2.9
In original point is sometimes number sometimes object
So I made explicit using suffix num to clarify usage
Simply call fireSliderEvent(2,5);
fireSliderEvent = (datasetnum,pointnum)=>{
let myLine=this.chartRef.current.chartInstance;
//console.log(JSON.stringify(JSON.decycle(this.chartRef.current),null,2));
var canvas = myLine.canvas;
var boundingRect = canvas.getBoundingClientRect();
var meta = myLine.getDatasetMeta(datasetnum);
// https://stackoverflow.com/questions/6157929/how-to-simulate-a-mouse-click-using-javascript
var mouseX = Math.round((boundingRect.left + meta.dataset._children[pointnum]._view.x) / (boundingRect.right - boundingRect.left) * canvas.width / myLine.currentDevicePixelRatio);
var mouseY = Math.round((boundingRect.top + meta.dataset._children[pointnum]._view.y) / (boundingRect.bottom - boundingRect.top) * canvas.height / myLine.currentDevicePixelRatio);
var oEvent = document.createEvent('MouseEvents');
oEvent.initMouseEvent('click', true, true, document.defaultView,
0, mouseX, mouseY, mouseX, mouseY,
false, false, false, false, 0, canvas);
canvas.dispatchEvent(oEvent);
}

Categories

Resources