Add more than one values in chart - javascript

I have issue with my chart. I would like to add more than one value in my chart which is generating from table(Add gold,gas) . Can anybody gives me any ideas to solve a problem?(chartjs library)
<table id="fetch" cellspacing="5" cellpadding="8" class="table" >
<tr>
<th>Date</th>
<th>Prize</th>
</tr>
<script type="text/javascript">
var dane = [
["2019-08-01",6.25],
["2019-09-01",4.15],
["2019-10-01",10.23],
["2019-11-01",7.56],
["2019-12-01",0.00],
["2020-01-01",12.43],
["2020-02-01",11.25],
["2020-03-01",13.64],
["2020-04-01",10.20],
["2020-05-01",15.32]],
fetch = document.getElementById('fetch');
for(var i=0; i <dane.length; i++){
var newRow = fetch.insertRow(fetch.length);
for(var j=0; j<dane[i].length; j++){
var cell = newRow.insertCell(j);
cell.innerHTML = dane[i][j];
}
}
</script>
<script>
const labels = [];
const data = {
labels: labels,
datasets: [{
label: 'Oil',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: dane,
}]
};
const config = {
type: 'line',
data: data,
options: {
},
};
</script>
example

Related

chart.js labels Left to Right

i want to invert labels from Left to Right.
what do i have?
a JSON File in which the data is coming from Google Sheet's App Script.
i Have Created a chart with the help of this JSON file and Chart.js
in this chart the Levels which is time is printed right to left.
What Do i need?
i want to print the levels from Left to Right.
Google Sheet App Script Code
labels Left to Rightfunction doGet(e) {
var sheet = SpreadsheetApp.getActive();
var nse = sheet.getSheetByName("Sheet3");
var data = [];
var rlen = nse.getLastRow();
var clen = nse.getLastColumn();
var rows = nse.getRange(1, 1, rlen, clen).getDisplayValues(); // Modified
for (var i = 1; i < rows.length; i++) {
var datarow = rows[i];
var record = {};
for (var j = 0; j < clen; j++) {
record[rows[0][j]] = datarow[j];
}
data.push(record);
}
var result = JSON.stringify(data);
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.JSON);
}
<div style="overflow: scroll;">
<canvas width="900" height="400" id="myChart"></canvas>
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script>
<script>
// setup
const data = {
labels: [],
datasets: [{
label: 'Nifty_PCR_COI',
data: [],
backgroundColor: [
'rgba(255, 26, 104, 0.2)'
],
borderColor: [
'rgba(255, 26, 104, 1)'
],
tension: 0.4,
},{
label: 'Bank_Nifty_PCR_COI',
data: [],
backgroundColor: [
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(54, 162, 235, 1)'
],
tension: 0.4,
}]
};
// config
const config = {
type: 'line',
data,
options: {
animation: false,
responsive: false,
scales: {
y: {
beginAtZero: true,
position: 'right'
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
//Json Fetch
getData();
async function getData() {
const response = await fetch(
'https://script.googleusercontent.com/macros/echo?user_content_key=r9CiwwP04Rh83CglKNwLbJw3zKlvAIWVj4Yf9a5cT3CPRmlxaBB9bOAMnkFV2os4ee10iaj9S7HNOU5axJWhdXmuYbHPVyWnm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnC4mxGG_R4juVl897H-HHcU5jBSu36oRyKZzBJteCuzXZ2p8eeHkRfjTV-mrMKhBOgim2y6bAoCZpSiZg9-Rh7EUjhE06fNngtz9Jw9Md8uu&lib=MQ0aMrcKwzFLX_7mD1gjcTxV-kV6j6m2N');
const jsondata = await response.json();
length = jsondata.length;
labels = [];
Nifty_PCR_COI = [];
Bank_Nifty_PCR_COI = [];
for (i = 0; i < length; i++) {
labels.push(jsondata[i].TimeCOI);
Nifty_PCR_COI.push(jsondata[i].Nifty_PCR_COI);
Bank_Nifty_PCR_COI.push(jsondata[i].Bank_Nifty_PCR_COI);
myChart.config.data.labels = labels;
myChart.config.data.datasets[0].data = Nifty_PCR_COI;
myChart.config.data.datasets[1].data = Bank_Nifty_PCR_COI;
myChart.update();
}
}
setInterval(getData, 5000)
</script>

Use an array as chart values

I need an array with chart values, I obtained one but after exiting from the function it became blank, here's what happens: Example
function AddvotoTec(votor) {
class Avg {
constructor() {}
static average(votor) {
var total = 0;
var count = 0;
jQuery.each(votor, function(index, value) {
total += value;
count++;
});
return total / count;
}
}
var mvoti = Avg.average(votor);
var mvoti = Math.round((mvoti + Number.EPSILON) * 10) / 10;
const myJSON = JSON.stringify(mvoti);
voti(myJSON);
}
var allvoti = [];
function voti(Voti) {
allvoti.push(Voti);
}
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: [
'rgb(255, 132, 0)'
],
borderColor: 'rgb(255, 99, 132)',
data: allvoti,
}]
};
The chart that I used is Chart.js.

hide labels and 0 values in chart.js?

I am beginner on this Chart.js and wanna ask, How can I hide the labels and 0 values in the bar Chart. I cannot just hide the whole Dataset since I am using a SQL Table to get the Values "into" Chart.Js. I just want the bar chart show only if the labels have the value. Need your help
sample chart
{
{
$.post("datachartasr.php",
function (data)
{
console.log(data);
var intake = [];
var active = [];
var inactive = [];
var deffered = [];
var widthdrawn = [];
var dis_ter_dereg = [];
var missing = [];
for (var i in data) {
intake.push(data[i].intake);
active.push(data[i].active);
inactive.push(data[i].inactive);
deffered.push(data[i].deffered);
widthdrawn.push(data[i].widthdrawn);
dis_ter_dereg.push(data[i].dis_ter_dereg);
missing.push(data[i].missing);
}
var chartdata = {
labels: intake,
datasets: [
{
label: 'Active Status',
backgroundColor: '#1E90FF',
borderColor: '#1E90FF',
hoverBackgroundColor: '#1E90FF',
hoverBorderColor: '#666666',
data: active
},
{
label: 'Deferred Status',
backgroundColor: '#708090',
borderColor: '#708090',
hoverBackgroundColor: '#708090',
hoverBorderColor: '#666666',
data: deffered
},
.....
.....
.....
]
};
var graphTarget = $("#graphCanvas");
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata,
});
});
}
}
You can have the below function inside data labels to hide the Zero value:
options: {
plugins: {
datalabels: {
display: function(context) {
return context.dataset.data[context.dataIndex] !== 0; // or >= 1 or ...
}
}
}
}
See more on this issue here https://github.com/chartjs/chartjs-plugin-datalabels/issues/6

How to have mutiple charts in a single page using Chart.js?

I tried to draw more than two charts with Chart.js on the same page and created a dynamic div in a loop with all the data for the chart like this:
<div class="col-4">
<canvas class="trend-chart" id="chart{{ p.sNo }}" width="500" height="100" role="img" data-pv="{{ p.recentPageViews }}">
</canvas>
</div>
The JavaScript code to dynamically create a charts based on the class name:
const labels = [
'22-12-12',
'22-12-13',
'22-12-14',
'22-12-15',
'22-12-16',
'22-12-17',
'22-12-18',
'22-12-19',
'22-12-20',
'22-12-21'
];
const config = {
type: 'line',
animation: true,
options: {}
};
var charts = document.getElementsByClassName("trend-chart");
for (var i = 0; i < charts.length; i++) {
pv = charts[i].getAttribute('data-pv');
id = charts[i].getAttribute('id');
window['config' + id] = config;
window['data' + id] = {
labels: labels,
datasets: [{
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: JSON.parse(pv),
}]
};
window['config' + id]['data'] = window['data' + id];
window['ctx' + id] = document.getElementById(id).getContext('2d');
window['myChart' + id] = new Chart(
window['ctx' + id],
window['config' + id]
);
}
Everything works fine except the tooltip when I mouse hover to the chart data points. I am not seeing the tooltip and I get the following error:
Uncaught TypeError: Cannot read properties of null (reading 'getLabelAndValue')
at Eo (chart.js:13)
at Ho._createItems (chart.js:13)
at Ho.update (chart.js:13)
at Ho.handleEvent (chart.js:13)
at Object.afterEvent (chart.js:13)
at Q (chart.js:13)
at Vs._notify (chart.js:13)
at Vs.notify (chart.js:13)
at hn.notifyPlugins (chart.js:13)
at hn._eventHandler (chart.js:13)*
Please add label property in the datasets as per below code.
datasets: [{
label: 'Some text',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: JSON.parse(pv),
}]
Hi figure it out how to fix it, the main issue the context is not setting properly so I did like below to overcome
window.addEventListener('load', function() {
var charts = document.getElementsByClassName("trend-chart");
for (var i = 0; i < charts.length; i++) {
pv = charts[i].getAttribute('data-pv');
id = charts[i].getAttribute('id');
new Chart(
document.getElementById(id).getContext('2d'), {
type: 'line',
animation: true,
data: {
labels: JSON.parse(charts[i].getAttribute('data-pvd')),
datasets: [{
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: JSON.parse(pv),
}]
},
options: {plugins: {......},scales: {......}}
}
);
}
});

How can I highlight a particular datapoint in chartjs, where my data is coming from json array?

// here I am taking another json encoded data from phpfile
$(document).ready(function () {
showGraph();
});
function showGraph()
{
{
$.post("phpfile.php",
function (data)
{
console.log(data);
var name = [];
var marks = [];
var height=[];
//and here as I couldn't encode two json array's separetly I'm declaring it to a variable and then using it
var jsonfile =[{"height":"85","st_name":"Name1"},{"height":"100","st_name":"Name3"},{"height":"92","st_name":"Name4"},{"height":"104","st_name":"Name5"},{"height":"91","st_name":"Name2"},{"height":"99","st_name":"Name6"},{"height":"140","st_name":"AI346"},{"height":"139","st_name":"abc"},{"height":"141","st_name":"def"},{"height":"140","st_name":"ghi"},{"height":"144","st_name":"jkl"},{"height":"130","st_name":"lmn"},{"height":"142","st_name":"opq"},{"height":"132","st_name":"rst"},{"height":"135","st_name":"xyz"},{"height":"135","st_name":"asdfsf"}];
//here I am reading the data from phpfile(1st Json array)
for (var i in data) {
name.push(data[i].st_name);
marks.push(data[i].height);
}
//here i am trying to access data from second json
for (var i=0;i<jsonfile.length;i++){
if(jsonfile[i].height==100)
{ height.push(jsonfile[i].height)}
}
//my graph function ,when I do this I am getting a single point with second json(height variable) but I need to highlight the particular point under a condition... I am not understanding how to do it.
var chartdata = {
labels: name,
datasets: [
{
label: 'height',
fill:false,
lineTension:0.5,
backgroundColor: '#5B2C6F',
borderColor: '#5B2C6F',
pointHoverBackgroundColor: '#5B2C6F',
pointHoverBorderColor: '#5B2C6F',
data: marks
//data:height
},
{
label: 'weight',
fill:false,
lineTension:0.1,
backgroundColor: '#C0392B',
borderColor: '#C0392B',
pointHoverBackgroundColor: '#C0392B',
pointHoverBorderColor: '#C0392B',
data:height,
//data:height
}
]
};
var graphTarget = $("#graphCanvas");
var lineGraph = new Chart(graphTarget, {
type: 'line',
data: chartdata,
options :{
scales:{
xAxes: [{
display: false //this will remove all the x-axis grid lines
}]
}
}
});
});
}
}
</script>
i will try to improve this.
var data =[{"height":"85","st_name":"Name1","color":"rgba(85, 85, 255, 255)"},{"height":"100","st_name":"Name3","color":"rgba(255, 0, 0, 2)"},{"height":"92","st_name":"Name4","color":"rgba(85, 85, 255, 255)"},{"height":"104","st_name":"Name5","color":"rgba(85, 85, 255, 255)"}];
var height = [];
var label = [];
var color = [];
for(i = 0; i<data.length; i++){
height.push(data[i]['height']);
label.push(data[i]['st_name']);
color.push(data[i]['color']);
}
var ctx = document.getElementById('myLine').getContext('2d');
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: label,
datasets: [{
data: height,
pointBorderColor: color,
}]
}
});

Categories