How to make chart js display values ​in real time? - javascript

I just learned to make a web And I want to know how to make chart js to display values ​​in real time. Can you guys advise or tell me how to do it for me?
var data = [];
var temp = [];
async function getRandomUser() {
const response = await fetch('http://localhost:1111/chartpie');
const data = await response.json();
addData(data);
}
function addData(object) {
temp.push(object.temperature);
var z = 80;
var y = z - temp;
var ctx = document.getElementById("myPieChart");
myPieChart = new Chart(ctx, {
type: "doughnut",
data: {
labels: ["Temperature", "Null"],
datasets: [{
data: [temp, y],
backgroundColor: [
"orange",
"rgba(0, 172, 105, 1)"
],
}]
},
options: {
legend: {
display: false
},
}
});
}
getRandomUser()
The values ​​I retrieved are the values ​​retrieved from mongoDB, fetched in the form of an array. Thank You!

You can just update the chart in "real time" by adding to the charts data array.
see: https://www.chartjs.org/docs/latest/developers/updates.html
Adding and removing data is supported by changing the data array. To
add data, just add data into the data array as seen in this example.
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
For example...
const canvas = document.getElementById('myChart');
canvas.height = 75;
const labels = [
'dju32',
'ad6b2',
'0f23f',
'asd4c',
];
const data = {
labels: labels,
datasets: [{
label: 'Test',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 4],
}]
};
const config = {
type: 'line',
data: data,
options: {}
};
const myChart = new Chart(
canvas,
config
);
// function to update the chart
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
// randomly add new data
setInterval(function() {
const newLabel = (Math.random() + 1).toString(36).substring(7);
const newData = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
addData(myChart, newLabel, newData);
}, 1000);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div>
<canvas id="myChart"></canvas>
</div>

Related

Display Percentage on HTML Tag by fetching percentage data from Doughnut Chart

I am new in JavaScript and I really want to know that how can we display data in form of percentage by fetching percentage data through doughnut chart using JS
<div class="block-text">
<div class="flex-chart"> <div class="box-file"></div><p class="spacing">abc</p>
<p id = "count">20%</p></div>
<div class="flex-chart"> <div class="box-url"></div><p class="spacing">xyz</p>
<p>30%</p>
</div>
</div>
Here is the Doughnut Chart JS code:
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<script>
// setup
const data = {
//labels: ['xyz', 'abc'],
datasets: [{
// label: 'Weekly Sales',
data: [12, 20],
backgroundColor: [
'rgb(254, 214, 10)',
'rgb(255, 90, 48)'
],
borderColor: [
"#ffffff",
],
borderWidth: 1
}]
};
// config
const config = {
type: 'doughnut',
data,
options: {
plugins: {
datalabels: {
formatter: (value, ctx) => {
let datasets = ctx.chart.data.datasets;
if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
var sum = datasets[0].data.reduce((a, b) => a + b, 0);
var percentage = Math.round((value / sum) * 100) + '%';
return percentage;
} else {
return percentage;
}
},
color: '#fff',
}
}
}
}
// render init block
const myChart = new Chart(
document.getElementById('chart'),
config
);
Now I want to display Percentage to get it from doughnut chart percentage variable and post it on 'abc' tag
abc
20%
I want percentage data in replace of 20% because 20% is static at this time
Check this code may be it will help you.
var data = [{
data: [50, 55, 60, 33],
labels: ["India", "China", "US", "Canada"],
backgroundColor: [
"#4b77a9",
"#5f255f",
"#d21243",
"#B27200"
],
borderColor: "#fff"
}];
var options = {
tooltips: {
enabled: false
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
let datasets = ctx.chart.data.datasets;
if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
let sum = datasets[0].data.reduce((a, b) => a + b, 0);
let percentage = Math.round((value / sum) * 100) + '%';
return percentage;
} else {
return percentage;
}
},
color: '#fff',
}
}
};
var ctx = document.getElementById("pie-chart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
datasets: data
},
options: options
});
JSFIDDLE

undefined labels piechart - chartjs

can you help me. i want show my data in percententage value. but my label is undefined. how i show my label to?
this my chart
var options = {
tooltips: {
custom: true
},
plugins: {
datalabels: {
display: true,
formatter: (value, ctx) => {
let datasets = ctx.chart.data.datasets;
if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
let sum = datasets[0].data.reduce((a, b) => a + b, 0);
let percentage = Math.round((value / sum) * 100) + '%';
return percentage;
} else {
return percentage;
}
},
color: '#fff',
}
}
};
var ctx = document.getElementById("pie-chart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
datasets: data
},
options: options
});
Labels array is not supposed to be in the dataset itself but is supposed to be in the main data object like so:
var data = [{
data: [50, 55, 60, 33],
backgroundColor: [
"#4b77a9",
"#5f255f",
"#d21243",
"#B27200"
],
borderColor: "#fff"
}];
var options = {
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value * 100 / sum).toFixed(2) + "%";
return percentage;
},
color: '#fff',
}
}
};
var ctx = document.getElementById("pie-chart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["India", "China", "US", "Canada"],
datasets: data
},
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.4.0/dist/chartjs-plugin-datalabels.min.js"></script>
<canvas id="pie-chart"></canvas>

Frontend and backend for chart using chartjs, mongodb, and controller

I am new to generating a chart using the ajax mechanism and chartjs. It seems that I managed to generate the graph but they are plotted incorrectly. Please enlighten me on how I could improve. Would really appreciate Thank you
Following is my code in javascript to plot chart
var ctx = document.getElementById('myChart').getContext('2d');
$.ajax({
url:"/dashboard",
type:"POST",
data: {},
error: function() {
alert("Error");
},
success: function(data, status, xhr) {
debugger
// declare all variables to draw chart
var chartDim = {};
var chartDim = data.chartDim;
var xLabels = data.labels;
var vLabels = [];
var vData = [];
let newValues =[]
// get from database to push to draw the chart
for (const [key, values] of Object.entries(chartDim)) {
vLabels.push(key);
let newValues = values.map(myFunction);
debugger;
vData.push(newValues);
}
debugger
var myChart = new Chart(ctx, {
data: {
labels: xLabels,
datasets: []
},
options: {
responsive: false
}
});
// draw to chart
debugger
for (i= 0; i < vLabels.length; i++ ) {
myChart.data.datasets.push({
label: vLabels[i],
type: "bar",
// borderColor: '#'+(0x1ff0000+Math.random()*0xffffff).toString(16).substr(1,6),
borderColor: '#'+(0x1100000+Math.random()*0xffffff).toString(16).substr(1,6),
backgroundColor: "rgba(249, 238, 236, 0.74)",
data: vData[i],
spanGaps: true
});
myChart.update();
}
}})
This happens because while making your chart you push each data point as a new dataset. Instead you just need to use a single dataset and pass the data array to it like so:
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: xLabels,
datasets: [{
borderColor: '#' + (0x1100000 + Math.random() * 0xffffff).toString(16).substr(1, 6),
backgroundColor: "rgba(249, 238, 236, 0.74)",
data: vData,
spanGaps: true
}]
},
options: {
responsive: false
}
});

How can I show extra data in chart.js tooltip?

I'm trying to show weight_id retrieved from mysql data in a chart.js tooltip (shown as (weight_ids[index]) in the image). And later, I intend to show a modal instead of a tooltip to let users update or delete that data. I presume I cannot achieve that without linking the linechart's point data with id stored in mysql. How can I incorporate this id data?
I would appreciate any help very much.
enter image description here
My code is as follows:
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>
{{-- グラフを描画--}}
<script>
//ラベル
const labels = #json($date_labels);
// id
const weight_ids = #json($weight_ids);
//体重ログ
const weight_logs = #json($weight_logs);
const aryMax = function(a, b) {
return Math.max(a, b);
};
const aryMin = function(a, b) {
return Math.min(a, b);
};
let min_label = Math.floor((weight_logs).reduce(aryMin) - 0.5);
let max_label = Math.ceil((weight_logs).reduce(aryMax) + 0.5);
console.log(weight_ids);
console.log(weight_logs);
console.log(min_label, max_label);
//グラフを描画
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data : {
labels: labels, // x軸ラベル
datasets: [
{
label: `Weight (weight_ids[index])`,
data: weight_logs,
tension: 0,
borderColor: "rgba(37,78,255,1)",
backgroundColor: "rgba(0,0,0,0)",
pointRadius: 3
}
]
},
options: {
title: {
display: false,
text: ''
},
legend: {
display: false,
},
scales: {
yAxes: [
{
ticks: {
min: min_label, // ラベル最小値
max: max_label, // ラベル最大値
},
scaleLabel: {
display: true,
fontSize: 16,
labelString: '体重 (kg)'
}
}
],
},
hover: {
mode: 'point'
},
onClick: function clickHandler(evt) {
var firstPoint = myChart.getElementAtEvent(evt)[0];
if (firstPoint) {
var label = myChart.data.labels[firstPoint._index];
var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
console.log(label);
console.log(value);
if (value) {
$('#weidhtModal').modal('show');
}
}
}
}
});
</script>
Thank you!
I found a way to retrieve weight_id using the following function.
onClick: function clickHandler(evt, activeElements) {
if (activeElements.length) {
var element = this.getElementAtEvent(evt);
var index = element[0]._index;
var _datasetIndex = element[0]._datasetIndex;
var weightId = weight_ids[index];
var weightLog = weight_logs[index];
console.log(index);
console.log(weightId);
console.log(this.data.labels[index]);
console.log(weightLog);
}
}

How to display different datasets from different ajax calls in the same ChartJS?

I'm trying to display different datasets, from different ajax calls, in the same chartJS.
The idea is to show different stats per month, on 13 consecutive months.
1 ajax call = 1 stat for each of the 13 months.
The JSON data for on stat looks like this :
[{"month":"June 2020","value":0},{"month":"May 2020","value":0},{"month":"April 2020","value":0},{"month":"March 2020","value":0},{"month":"February 2020","value":30},{"month":"January 2020","value":182},{"month":"December 2019","value":143},{"month":"November 2019","value":111},{"month":"October 2019","value":103},{"month":"September 2019","value":128},{"month":"August 2019","value":71},{"month":"July 2019","value":129},{"month":"June 2019","value":98}]
Of course, the values determinate the bars, and the months are the chart's labels.
I can display one stat for every month, but I can't add the others (3 more stats to show).
The expected result : 4 bars for each month.
Here is my working code for one dataset :
function getJsonDataForStat1() {
return $.ajax
({
url: 'getJsonDataForStat1',
type: 'get'
});
}
function setChart() {
$.when(getJsonDataForStat1()).done(function (stats) {
stats = JSON.parse(stats);
var data = [], labels = [];
stats.forEach(function (s) {
labels.push(s.month);
data.push(s.value);
});
var ctx = document.getElementById('graph').getContext('2d');
var graph = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [
{
label: 'stat 1',
data: data,
backgroundColor: '#735288',
borderColor: '#3c8dbc',
borderWidth: 1
}],
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
});
});
}
How to add the 3 others ?
Any help would be appreciated.
Thanks a lot !
Let's suppose you fetched your data and have multiple statistics/arrays containing the data for each month.
You can compute a lookup that maps the month to the values of the different statistics.
The labels are simply the keys, although you'd probably want to sort them based on the date. The datasets can easily be computed by mapping the labels.
var lkp = [stat1, stat2].flat().reduce((acc, cur) => {
const {
month,
value
} = cur;
acc[month] = acc[month] || [];
acc[month].push(value);
return acc;
}, {});
//{'June 2020': [0, 10], ...}
var labels = Object.keys(lkp).sort((a, b) => (Date.parse(a) % (1000 * 60 * 60 * 24 * 365)) - (Date.parse(b) % (1000 * 60 * 60 * 24 * 365)))
// ['June 2020', 'May 2020']
var colors = ['red', 'green'];
var datasets = [0, 1].map((index) => {
const data = labels.map(label => lkp[label][index]);
return {
data,
label: `Statistic ${index}`,
backgroundColor: colors[index],
}
});
var options = {
type: 'bar',
data: {
labels,
datasets,
},
options: {
scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
}
}
}
var ctx = document.getElementById('chart').getContext('2d');
try {
new Chart(ctx, options);
} catch (e) {
//catch co error
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>
<script>
var stat1 = [{"month":"June 2020","value":0},{"month":"May 2020","value":0},{"month":"April 2020","value":0},{"month":"March 2020","value":0},{"month":"February 2020","value":30},{"month":"January 2020","value":182},{"month":"December 2019","value":143},{"month":"November 2019","value":111},{"month":"October 2019","value":103},{"month":"September 2019","value":128},{"month":"August 2019","value":71},{"month":"July 2019","value":129},{"month":"June 2019","value":98}]
var stat2 = [{"month":"June 2020","value":10},{"month":"May 2020","value":25},{"month":"April 2020","value":75},{"month":"March 2020","value":80},{"month":"February 2020","value":30},{"month":"January 2020","value":182},{"month":"December 2019","value":23},{"month":"November 2019","value":123},{"month":"October 2019","value":50},{"month":"September 2019","value":128},{"month":"August 2019","value":71},{"month":"July 2019","value":129},{"month":"June 2019","value":98}];
</script>
<canvas id="chart" width="600" height="400"></canvas>
I have finally succeeded, based on Martin M.'s idea.
Here is my code (maybe it can help someone who has the same issue).
It works perfectly.
var graph = setChart();
updateChart();
function setChart() {
$.when(getData1()).done(function (stats) {
stats = JSON.parse(stats);
var data = [], labels = [];
stats.forEach(function (s) {
labels.push(s.month);
data.push(s.value);
});
var ctx = document.getElementById('graph').getContext('2d');
return graph = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [
{
label: 'data 1',
data: data,
backgroundColor: '#00c0ef',
}],
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
});
});
}
function updateChart() {
$.when(setChart()).done(function () {
// I've repeated the following block for data 3 and 4 (still inside updateChart())
$.when(getData2()).done(function (stats) {
stats = JSON.parse(stats);
var data = [];
stats.forEach(function (s) {
data.push(s.value);
});
var dataset = {};
dataset.label = "data 2";
dataset.backgroundColor = '#061834';
dataset.data = data;
graph.data.datasets.push(dataset);
graph.update();
})
})
}
Thank you all for your help !

Categories

Resources