1 year ago
#382156
Fotini K.
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
django
websocket
chart.js
real-time-data
0 Answers
Your Answer