How to display stacked line chartjs - chart.js

I try to display stacked line chart but it doesn't work.
Could you advise where I should change with the following code?
window.onload=function(){
var ctx = document.getElementById("myChart").getContext("2d");
var data = {
labels: {{subcategories|tojson}},
datasets: [
{
1st_sample_dataset
},
{
2nd_sample_dataset
}
]
},
options = {
scales: {
yAxes: [{
stacked: true
}]
}
};
new Chart(ctx).Line(data, {
onAnimationComplete: function () {
var sourceCanvas = this.chart.ctx.canvas;
var targetCtx = document.getElementById("myChartAxis").getContext("2d");
targetCtx.canvas.width = copyWidth;
targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth, copyHeight, 0, 0, copyWidth, copyHeight);
}
});
}
And this is actual display.

From your code I presume you're using an old version of chart.js.
new Chart(ctx).Line(data, {
...
Charts are now created in a different way.
var myChart = new Chart(ctx, {
type: 'line',
...
If you switch to version 2.9.3., it works fine as the following code sample illustrates.
new Chart(document.getElementById('myChartAxis'), {
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [
{
label: 'WARNINGS',
data: [1, 2, 3, 2],
borderColor: 'rgb(255, 159, 64)',
backgroundColor: 'rgba(255, 159, 64, 0.2)'
},
{
label: 'ERRORS',
data: [1, 2, 1, 3],
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(255, 99, 132, 0.2)'
}
]
},
options: {
scales: {
yAxes: [{
stacked: true
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChartAxis" height="90"></canvas>

Related

Add multiple real-time plots on the same page with Chart.js (Django)

i'm trying to add multiple real-time plots on the same page (Django framework) with Chart.js using websockets. When i try to add separate socket on the 2nd plot, the 1st freezes. Here is my code, thanks a lot. I'm sure there is a better way to write code, but I'm relatively new to js.
<script>
let socket =new WebSocket('ws://localhost:8000/ws/polData/');
socket.onopen =function(e){
alert('Connection established');
};
socket.onmessage = function(e){
console.log(e.data);
var recData=JSON.parse(e.data);
dataObjNew=dataObj['data']['datasets'][0]['data'];
dataObjNew.shift();
dataObjNew.push(recData.value);
dataObj['data']['datasets'][0]['data']=dataObjNew;
window.myLine.update();
};
socket.onclose = function(e){
alert('Connection CLosed');
};
</script>
<script>
var dataObj={
type: 'line',
data: {
labels: [1,2,3,4,5,6],
datasets: [{
label: 'Real time data',
borderColor: "#1d7af3",
pointBorderColor: "#FFF",
pointBackgroundColor: "#1d7af3",
pointBorderWidth: 2,
pointHoverRadius: 4,
pointHoverBorderWidth: 1,
pointRadius: 4,
backgroundColor: 'transparent',
fill: true,
borderWidth: 2,
data: [12, 19, 3, 5, 2, 3],
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
position: 'bottom',
labels : {
padding: 10,
fontColor: '#1d7af3',
}
},
tooltips: {
bodySpacing: 4,
mode:"nearest",
intersect: 0,
position:"nearest",
xPadding:10,
yPadding:10,
caretPadding:10
},
layout:{
padding:{left:15,right:15,top:15,bottom:15}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
var ctx = document.getElementById('lineChart').getContext('2d');
window.myLine = new Chart(ctx,dataObj );
</script>
<script>
let socket =new WebSocket('ws://localhost:8000/ws/polData2/');
socket.onopen =function(e){
alert('Connection established');
};
socket.onmessage = function(e){
console.log(e.data);
var recData=JSON.parse(e.data);
dataObjNew2=dataObj2['data']['datasets'][0]['data'];
dataObjNew2.shift();
dataObjNew2.push(recData.value);
dataObj2['data']['datasets'][0]['data']=dataObjNew2;
window.myLine.update();
};
socket.onclose = function(e){
alert('Connection CLosed');
};
</script>
<script>
var dataObj2={
type: 'bar',
data: {
labels: [1,2,3,4,5,6],
datasets: [{
label: "Sales",
backgroundColor: 'rgb(23, 125, 255)',
borderColor: 'rgb(23, 125, 255)',
data: [12, 19, 3, 5, 2, 3],
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
}
}
var ctx2 = document.getElementById('barChart').getContext('2d');
window.myLine = new Chart(ctx2,dataObj2 );
</script>
polData is just random values from a script

How to make the x-axis start from zero in chartjs-plugin-streaming?

I'm working on a project that could display sensing data on local web pages in real time with Django and I made this stream live data chart. But I don't need to this realtime x-axis ticks. I want to make the x-axis starting at zero and increasing 1 step by one second.
I think "xAxes type realtime" is the key, but I'm new to this and it's hard for me to solve alone, so I need your help.
enter image description here
<script>
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
function onRefresh(chart) {
var now = Date.now();
chart.data.datasets.forEach(function(dataset) {
dataset.data.push({
x: now,
y: GetData()
});
});
}
var color = Chart.helpers.color;
var config = {
type: 'line',
data: {
datasets: [{
backgroundColor: [
'rgba(100, 200, 200, 0)'
],
borderColor: chartColors.blue,
fill: false,
lineTension: 0,
borderDash: [8, 0],
data: [],
borderWidth:3,
pointRadius:0,
}]
},
options: {
legend:{
display:false
},
title: {
display: true,
text: 'Some Chart',
fontSize:20,
fontFamily:"Tahoma"
},
scales: {
xAxes: [{
ticks:{
beginAtZero: true
},
gridLines:{
display:true
},
type: 'realtime',
display:true,
position:'bottom',
realtime: {
duration: 20000,
refresh: 1000,
delay: 0,
onRefresh: onRefresh
}
}],
yAxes: [{
gridLines:{
display:true
},
scaleLabel: {
display: true,
labelString: 'value'
}
}]
},
}
};
window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
window.myChart = new Chart(ctx, config);
};
</script>
Is there any other way to make streaming live graph with Django, please let me know.
I solved this myself. The key was about 'xAxes ticks callback'. thank you.

Changing grid color in radar chart

//radar-chart
const data = {
labels: [
'Stick Slip',
'Whirl',
'Bit Balling',
'Bit Bounce',
'test'
],
datasets: [{
label: 'My First Dataset',
data: [0.2, 0.5, 0, 0, 1],
fill: true,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgb(255, 99, 132)',
pointBackgroundColor: 'rgb(255, 99, 132)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(255, 99, 132)'
},]
};
const config = {
maintainAspectRatio: false,
elements: {
line: {
borderWidth: 3,
}
},
scales: {
r: {
suggestedMin: 0,
suggestedMax: 1,
angleLines: {
color: 'red'
}
},
},
}
var ctx = document.getElementById('radar-chart-dysfunctions');
var myRadarChart = new Chart(ctx, {
type: 'radar',
data: data,
options: config,
});
How can I change the grey gridlines to another color?
This is my code: https://codepen.io/bahrikutlu/pen/QWdaEMp
I have found various solutions on Stack Overflow such as following but it does not work with version 3.0
With Chartjs Radar - how to modify the gray gridlines?
Thanks
You will have to edit the color of the grid in the scale option like the example below
var options = {
type: 'radar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
}]
},
options: {
scales: {
r: {
grid: {
color: 'red'
}
}
}
}
}
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.0.2/chart.js" integrity="sha512-n8DscwKN6+Yjr7rI6mL+m9nS4uCEgIrKRFcP0EOkIvzOLUyQgOjWK15hRfoCJQZe0s6XrARyXjpvGFo1w9N3xg==" crossorigin="anonymous"></script>
</body>

Can I offset the bars in chart.js stacked bar chart?

Can I offset the bars in the chart.js stacked bar chart like so:
Based on this answer, I created a runnable code snippet that illustrates how it could be done. I'm not using stacked bars because the use case is not clear to me and the image from the question rather looks like a bar with shadows.
const dataset = [40, 80, 50, 60, 70];
const offset = 8;
Chart.pluginService.register({
afterUpdate: function(chart) {
var dataset = chart.config.data.datasets[1];
for (var i = 0; i < dataset._meta[0].data.length; i++) {
var model = dataset._meta[0].data[i]._model;
model.x += offset;
model.controlPointNextX += offset;
model.controlPointPreviousX += offset;
}
}
});
var data = {
labels: ["A", "B", "C", "D", "E"],
datasets: [{
backgroundColor: [
'rgba(255, 99, 132)',
'rgba(255, 206, 86)',
'rgba(54, 162, 235)',
'rgba(75, 192, 192)',
'rgba(153, 102, 255)'
],
borderWidth: 1,
data: dataset,
xAxisID: "bar-x-axis1",
categoryPercentage: 0.5,
barPercentage: 0.5,
},
{
backgroundColor: 'rgba(0, 0, 0, 0.2)',
data: dataset.map(v => v + offset),
xAxisID: "bar-x-axis2",
categoryPercentage: 0.5,
barPercentage: 0.5
}
]
};
var options = {
legend: {
display: false
},
tooltips: {
enabled: false
},
scales: {
xAxes: [
{
id: "bar-x-axis2"
},
{
id: "bar-x-axis1",
offset: true,
ticks: {
display: false
}
}
],
yAxes: [{
id: "bar-y-axis1",
ticks: {
beginAtZero: true,
stepSize: 50
}
}]
}
};
var ctx = document.getElementById("myChart").getContext("2d");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="60"></canvas>
For Chart.js v3, you can use a different approach.
In the beforeDatasetsDraw, you save the define the shadow properties on the canvas through CanvasRenderingContext2D. Make sure to first save the state of the rendering context by invoking ctx.save().
In the afterDatasetsDraw hook, you need to restore the state of the rendering context by invoking ctx.restore().
Convert the bars into floating bars through data: data.map(v => [-20, v]) to makes sure, the shadows appear from the base of the bars.
Define a tooltip.callbacks.label function that provides the initial values in the tooltips.
Please take a look at below runnable code and see how it works.
const data = [40, 80, 50, 60, 70];
const offset = 10;
new Chart('myChart', {
type: 'bar',
plugins: [{
beforeDatasetsDraw: chart => {
const ctx = chart.ctx;
ctx.save();
ctx.shadowOffsetX = offset;
ctx.shadowOffsetY = -offset;
ctx.shadowBlur = 5;
ctx.shadowColor = 'rgb(220, 220, 220)';
},
afterDatasetsDraw: chart => chart.ctx.restore()
}],
data: {
labels: ["A", "B", "C", "D", "E"],
datasets: [{
label: 'My Data',
data: data.map(v => [-20, v]),
backgroundColor: [
'rgba(255, 99, 132)',
'rgba(255, 206, 86)',
'rgba(54, 162, 235)',
'rgba(75, 192, 192)',
'rgba(153, 102, 255)'
],
categoryPercentage: 0.8
}]
},
options: {
plugins: {
tooltip: {
callbacks: {
label: ctx => data[ctx.dataIndex]
}
}
},
scales: {
y: {
min: 0,
max: Math.max(...data) + offset
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>

My last column does not show, I use chart.js 2.5

My last column does not show, I use chart.js 2.5,the framework is used laravel 5.4,the data has been confirmed into the incoming.
Look at this figure:
data has been into the incoming :
var ctxBar = $('#barChart');
var data2 = {
labels: {!!json_encode($project_names, JSON_UNESCAPED_UNICODE) !! },
datasets: [{
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
],
borderWidth: 2,
data: {!!json_encode(TasksCountArray($projects), JSON_UNESCAPED_UNICODE) !! }
}]
};
var myBarChart = new Chart(ctxBar, {
type: 'bar',
data: data2,
options: {
responsive: true,
title: {
display: true,
text: 'Projects Tasks'
},
legend: {
display: false
},
fullWidth: true
}
});