How to update data from ajax call (chart.js) - javascript

I manage to generate a graph from an ajax call coming from a php file.
I want to modify this graphic from the selection of the customers field (chg_customer) via a drop-down list. My drop-down list works and shows the names of the customers. However, I cannot generate a new chart from this selection with the right number (count) corresponding to the right customer. Can you help me ? thank you
html :
<select id="filter">
<option>Tous</option>
</select>
<canvas id="graph4Canvas" style="height: 700px; width: 100%;"></canvas></select>
graph.js :
$(document).ready(function() {
$.ajax({
url: 'graph4.php',
type: 'GET',
dataType: 'json',
success: function(data) {
var chg_customer = [];
var count = [];
for (var i in data) {
chg_customer.push(data[i].chg_customer);
count.push(data[i].count);
}
var ctx = $('#graph4Canvas');
const barGraph = new Chart(document.getElementById('graph4Canvas'), {
type: 'bar',
data: {
labels: data.map(o => o.chg_customer),
datasets: [{
label: 'Clients',
data: data.map(o => o.count),
backgroundColor: "rgba(0, 0, 255, 0.5)",
yAxisID: 'Nombres',
xAxisID: 'Clients',
}]
},
options: {
scales: {
yAxes: [{
id: "Nombres",
ticks: {
beginAtZero: true,
stepSize: 1,
fontSize: 15,
},
scaleLabel: {
display: true,
labelString: 'Nombres'
},
gridLines: {
drawOnChartArea: false
},
}],
xAxes: [{
id: "Clients",
ticks: {
beginAtZero: true,
stepSize: 1,
fontSize: 10,
},
scaleLabel: {
display: false,
},
gridLines: {
drawOnChartArea: false
},
}],
},
title: {
display: false,
},
legend: {
display: false,
},
},
});
data.forEach(o => {
const opt = document.createElement('option');
opt.value = o.chg_customer;
opt.appendChild(document.createTextNode(o.chg_customer));
document.getElementById('filter').appendChild(opt);
});
$("#filter").change(function() {
//update data
});

There isn't a need to generate a new chart. Once the chart exists all you need to do is to edit the datasets and call the chart update function to re-render the chart.
e.g (example is using angular in my case but still should apply):
HTML:
<mat-select [(value)]="selectedFilter" (selectionChange)="filterStreamType()">
JS:
public filterStreamType() {
// code manipulates data....
this.chart.data.datasets = newData; // update our dataset so chart js can re-draw it
this.chart.update(); // This is a redundant call but I did a bad job here and mixed some things that should not be mixed and so
}
Also note that between V2 and V3 there have been breaking changes so this syntax may vary a bit depending on the version you use.

Related

Equivalent of $.fn. of jQuery in Vanilla JS

Last few days I've been trying to convert this code to pure JS, but no luck until now...
This code basically starts a new Chart.JS instance when called via jQuery object.
(function ($) {
$.fn.createChartLine = function (labels, datasets, options) {
var settings = $.extend({}, $.fn.createChartLine.defaults, options);
this.each(function () {
let ctx = $(this);
new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: datasets
},
options: {
scales: {
y: {
title: {
display: true,
text: settings.labelString
},
beginAtZero: true
}
},
plugins: {
legend: {
display: settings.display_legend,
position: settings.legend_position,
labels: {
usePointStyle: settings.legend_pointStyle
}
}
}
}
});
});
};
$.fn.createChartLine.defaults = {
display_legend: true,
legend_position: 'top',
legend_pointStyle: true,
labelString: 'Clicks'
};
})(jQuery);
The initialization of a new chartline using the code above:
$("#chart1").createChartLine(['1', '2', '3'], [{
label: 'Clicks',
backgroundColor: Chart.helpers.color('#007bff').alpha(0.75).rgbString(),
borderColor: '#007bff',
data: [34, 56, 28],
borderWidth: 2,
tension: 0.4
}], {display_legend: false});
I tried thousands of ways to remove jQuery from it, but no luck. The intention is to get rid of jQuery in some pages, but this script is essential because with it I can create many Chart.JS instances in same page without needing repeating that amount of code.
I'm aiming to get something like this:
document.getElementById('chart1').createChartLine(...);
Is it possible?
This assumes you are using a version of ChartJS that accepts HTMLCanvasElement and other non-jQuery wrapped Elements to the new Chart() constructor.
You shouldn't extend the prototype of native elements, instead you should create a new function that gets the element(s) passed in.
// Instead of
document.getElementById('chart1').createChartLine(...);
// You'll want
createChartLine(document.getElementById('chart1'), ...);
or something similar.
I'd actually not pass in the element, but rather a selector, since that most closely matches how the jQuery plugin is working.
function createChartLine(selector, labels, datasets, options = {}) {
const settings = Object.assign(
{},
{
display_legend: true,
legend_position: "top",
legend_pointStyle: true,
labelString: "Clicks",
},
options
);
const elements = document.querySelectorAll(selector);
const charts = [];
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
const newChart = new Chart(element, {
type: "line",
data: {
labels: labels,
datasets: datasets,
},
options: {
scales: {
y: {
title: {
display: true,
text: settings.labelString,
},
beginAtZero: true,
},
},
plugins: {
legend: {
display: settings.display_legend,
position: settings.legend_position,
labels: {
usePointStyle: settings.legend_pointStyle,
},
},
},
},
});
charts.push(newChart);
}
return charts;
}
Here is how you'd call the function.
createChartLine(
"#chart1", // This is the new argument, the selector of the element you are initializing
["1", "2", "3"],
[
{
label: "Clicks",
backgroundColor: Chart.helpers.color("#007bff").alpha(0.75).rgbString(),
borderColor: "#007bff",
data: [34, 56, 28],
borderWidth: 2,
tension: 0.4,
},
],
{ display_legend: false }
);

How to add percentage after value data in chart

I need after each value to be a percent symbol ( % ) For example: 12% instead of 12
The below code in write in laravel php for the chartpie.
<script src="{{asset('assets/admin/js/vendor/apexcharts.min.js')}}"></script>
<script src="{{asset('assets/admin/js/vendor/chart.js.2.8.0.js')}}"></script>
<script>
var ctx = document.getElementById('tokenomi');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels:<?=$label?>,
datasets: [{
data:<?=$values?>,
],
borderColor: [
'rgba(231, 80, 90, 0.75)'
],
borderWidth: 0,
}]
},
options: {
aspectRatio: 1,
responsive: true,
maintainAspectRatio: true,
elements: {
line: {
tension: 0 // disables bezier curves
}
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}]
},
legend: {
display: false,
}
}
});
</script>
Check the current chart pie below, I tried a lot but I can't find a solution.
How do I add percent sign (%) behind of all values
Thanks
You need to define a tooltips.callback.label function as shown below. For further details please consult Chart.js v. 2.8.0 documentation here.
options: {
...
tooltips: {
callbacks: {
label: (tooltipItem, data) => data.datasets[0].data[tooltipItem.index] + '%'
}
},
...
Please note that you're using a rather old version of Chart.js, the today latest stable version is 3.7.0.

ChartJS Separate Labels for each dataset/independent datasets?

I'm essentially attempting to create a bar chart with 2-8 items where the label on the bottom/legend is the short product code(ex: 4380) and mousing over the bar shows the full SKU/product name.
I have gotten it mostly working but my implementation goes one of two undesirable ways.
The data points all combine into the first product number/chart label.
The blank spots make the bars tiny/not fill up the full width.
My code for rendering the chart is as follows:
var myBarChart2;
$.ajax({
url: "chartdata.php",
data: {
"skugroup": group
},
method: 'GET',
dataType: 'json',
success: function (d) {
Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#292b2c';
var ctx = document.getElementById("inventorybarchart");
myBarChart2 = new Chart(ctx, {
type: 'bar',
data: {
labels: d.labels,
datasets: d.datasets,
},
options: {
scales: {
xAxes: [{
gridLines: {
display: false
},
ticks: {
display: true
}
}],
yAxes: [{
ticks: {
min: 0,
beginAtZero: true
},
gridLines: {
display: true
}
}],
},
legend: {
display: false
}
}
});
}
});
The ajax response for the two versions is as follows:
Version 1:
{"datasets":[{"labels":"GRAY-DARK-GRAY","backgroundColor":"rgba(164,222,164,1)","borderColor":"rgba(164,222,164,1)","data":[5996]},{"labels":"CANARY-YELLOW","backgroundColor":"rgba(35,148,58,1)","borderColor":"rgba(35,148,58,1)","data":[4605]},{"labels":"PINK-WHITE-GRAY","backgroundColor":"rgba(101,24,125,1)","borderColor":"rgba(101,24,125,1)","data":[1288]},{"labels":"SEAFOAM-WHITE-GRAY","backgroundColor":"rgba(129,74,64,1)","borderColor":"rgba(129,74,64,1)","data":[3463]},{"labels":"YELLOW-WHITE-GRAY","backgroundColor":"rgba(91,216,70,1)","borderColor":"rgba(91,216,70,1)","data":[1537]},{"labels":"WHITE-YELLOW","backgroundColor":"rgba(101,225,237,1)","borderColor":"rgba(101,225,237,1)","data":[152]}],"labels":["4380","4311","4571","4588","4557","4373"]}
Version 2:
{"datasets":[{"label":"GRAY-DARK-GRAY","backgroundColor":"rgba(1,1,235,1)","borderColor":"rgba(1,1,235,1)","data":[5996,null,null,null,null]},{"label":"CANARY-YELLOW","backgroundColor":"rgba(12,87,184,1)","borderColor":"rgba(12,87,184,1)","data":[null,4605,null,null,null]},{"label":"PINK-WHITE-GRAY","backgroundColor":"rgba(85,107,126,1)","borderColor":"rgba(85,107,126,1)","data":[null,null,1288,null,null]},{"label":"SEAFOAM-WHITE-GRAY","backgroundColor":"rgba(181,150,65,1)","borderColor":"rgba(181,150,65,1)","data":[null,null,null,3463,null]},{"label":"YELLOW-WHITE-GRAY","backgroundColor":"rgba(132,66,28,1)","borderColor":"rgba(132,66,28,1)","data":[null,null,null,null,1537]},{"label":"WHITE-YELLOW","backgroundColor":"rgba(49,195,217,1)","borderColor":"rgba(49,195,217,1)","data":[null,null,null,null,null]}],"labels":["4380","4311","4571","4588","4557","4373"]}
The only difference is either I always use the 0 indexes for datasets[index].data or I fill in null depending on where it should be.
Should I be changing the way the chart is rendered or should I change the way the data is passed in?
For the record, the mouseover shows the proper sku/full name.
I would define the data in a single dataset and keep the full product names in a separate property.
const data = {
"labels": ["4380", "4311", "4571", "4588", "4557", "4373"],
"productNames": ["GRAY-DARK-GRAY", "CANARY-YELLOW", "PINK-WHITE-GRAY", "SEAFOAM-WHITE-GRAY", "YELLOW-WHITE-GRAY", "WHITE-YELLOW"],
"datasets": [{
"data": [5996, 4605, 1288, 3463, 1537, 152],
...
}]
};
To get the product names displayed in the tooltip, you would have to define a label callback function as follows:
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
let i = tooltipItem.index;
return data.productNames[i] + ': ' + data.datasets[0].data[i];
}
}
}
Please take a look at your amended code and see how it works.
const data = {
"labels": ["4380", "4311", "4571", "4588", "4557", "4373"],
"productNames": ["GRAY-DARK-GRAY", "CANARY-YELLOW", "PINK-WHITE-GRAY", "SEAFOAM-WHITE-GRAY", "YELLOW-WHITE-GRAY", "WHITE-YELLOW"],
"datasets": [{
"data": [5996, 4605, 1288, 3463, 1537, 152],
"backgroundColor": ["rgba(1,1,235,1)", "rgba(12,87,184,1)", "rgba(85,107,126,1)", "rgba(181,150,65,1)", "rgba(132,66,28,1)", "rgba(49,195,217,1)"],
"borderColor": ["rgba(1,1,235,1)", "rgba(12,87,184,1)", "rgba(85,107,126,1)", "rgba(181,150,65,1)", "rgba(132,66,28,1)", "rgba(49,195,217,1)"]
}]
};
var ctx = document.getElementById("inventorybarchart");
myBarChart2 = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}],
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
let i = tooltipItem.index;
return data.productNames[i] + ': ' + data.datasets[0].data[i];
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.0/Chart.min.js"></script>
<canvas id="inventorybarchart" height="90"></canvas>

ChartJS, Primeng, Gap first and end of line chart

I am using primeng chart component which uses chartjs. We are using chartjs 2.5.0 alongside primeng 4.0 and angular 4.
I created a dynamic chart and I put the data into chart after it came to us through some services. The problem is, after a while chartjs will put a gap at first and end of the chart.
Here is our options for chartjs:
this.options = {
responsive: true,
tooltips: {
mode: 'index',
intersect: false, // all points in chart to show tooltip
callbacks: { // adding labels as title in tooltip
title: function(tooltipItems, data) {
let date = tooltipItems[0].xLabel;
return me._rhDatePipe.transform(date, 'time');
}
}
},
hover : {
mode: 'index',
intersect: false
},
scales: {
xAxes: [{
type: 'time',
display: false, // preventing labels from being displayed
max: 20
}],
yAxes: [{
ticks: {
maxTicksLimit: 3
}
}]
}
}
and here is our first data settings:
this.data = {
labels: this.labels, // current time as label
datasets: [
{
label: me._messageService.translate('chart-label-buy'),
data: this.buyingData,
fill: false,
borderColor: "#2453db",
lineTension: 0,
borderWidth: 1.5,
radius: 0 // removing dot points on chart
},
{
label: me._messageService.translate('chart-label-sale'),
data: this.sellingData,
fill: false,
borderColor: "#f44336",
borderWidth: 1.5,
lineTension: 0,
radius: 0 // removing dot points on chart
},
{
label: me._messageService.translate('chart-label-last-trade'),
data: this.lastPriceData,
fill: false,
borderColor: "#000000",
lineTension: 0,
borderWidth: 1.5,
radius: 0 // removing dot points on chart
}
]
}
and here is the loop which will update the chart:
if(sortedKeysList != null) {
for(let key in sortedKeysList) {
let currentTime: number = sortedKeysList[key];
// just add new points
if(!this.currentTimes.includes(currentTime)) {
let date = new Date(currentTime);
this.labels.push(date);
this.currentTimes.push(currentTime);
this.buyingData.push(this.bestLimitsChart[currentTime].buy);
this.sellingData.push(this.bestLimitsChart[currentTime].sale);
if(this.bestLimitsChart[currentTime].price != 0)
this.lastPriceData.push(this.bestLimitsChart[currentTime].price);
else
this.lastPriceData.push(null);
this.updateChart();
}
}
}
and the picture of chart:
I do not know what is going on. Any helps will greatly appreciated.
I finally found the problem,
for other people facing this issue, you can add unit to your axis:
xAxes: [{
type: 'time',
time: {
displayFormats: {
minute: 'h:mm', // formatting data in labels
},
unit: 'minute' // destroy first and end gaps
},
display: false, // preventing labels from being displayed
}],
similar issue on github:
https://github.com/chartjs/Chart.js/issues/2277#issuecomment-314662961

Hide Y-axis labels when data is not displayed in Chart.js

I have a Chart.js bar graph displaying two sets of data: Total SQL Queries and Slow SQL Queries. I have Y-axis labels for each respective set of data. The graph can be seen below:
When I toggle one of the sets of data to not display, the corresponding Y-axis labels still display. When interpreting the graph, this is a bit confusing. As seen below:
My question: How can I hide the Y-axis labels of any set of data that is currently not being displayed?
This is how I currently have my chart set up:
<canvas id="SQLPerformanceChart" minHeight="400"></canvas>
<script type="text/javascript">
...
var data = {
labels: labelArray,
datasets: [{
label: "Total SQL Queries",
fill: false,
borderWidth: 1,
borderColor: "green",
backgroundColor: "rgba(0, 255, 0, 0.3)",
yAxisID: "y-axis-0",
data: totalQueriesArray
}, {
label: "Slow SQL Queries",
fill: false,
borderWidth: 1,
borderColor: "orange",
backgroundColor: "rgba(255, 255, 0, 0.3)",
yAxisID: "y-axis-1",
data: slowQueriesArray,
}]
};
var options = {
animation: false,
scales: {
yAxes: [{
position: "left",
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'Total SQL Queries'
},
id: "y-axis-0"
}, {
position: "right",
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'Slow SQL Queries'
},
id: "y-axis-1"
}]
},
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
title: function(tooltipItem, data) {
return data.label;
},
beforeLabel: function(tooltipItem, data) {
if (tooltipItem.index == 24) {
return data.labels[tooltipItem.index] + " - Now";
} else {
return data.labels[tooltipItem.index] + " - " + data.labels[(tooltipItem.index) + 1];
}
}
}
}
}
var ctx = document.getElementById("SQLPerformanceChart");
var SQLPerformanceChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
</script>
You can add a callback function to legends onClick:
var options = {
animation: false,
scales: {
yAxes: [{
position: "left",
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'Total SQL Queries'
},
id: "y-axis-0"
}, {
position: "right",
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'Slow SQL Queries'
},
id: "y-axis-1"
}]
},
legend: {
onClick: function(event, legendItem) {
//get the index of the clicked legend
var index = legendItem.datasetIndex;
//toggle chosen dataset's visibility
SQLPerformanceChart.data.datasets[index].hidden =
!SQLPerformanceChart.data.datasets[index].hidden;
//toggle the related labels' visibility
SQLPerformanceChart.options.scales.yAxes[index].display =
!SQLPerformanceChart.options.scales.yAxes[index].display;
SQLPerformanceChart.update();
}
}
}
This solution applies if you are using angular-chartjs, and if you want to apply this behaviour to all displayed charts.
If you want to skip to the code, check this fiddlejs.
You can also check this other fiddlejs to check the default Angular-Chartjs behaviour.
Step by step:
I use the first chart example in angular-chart.js, so this will be the final result after clicking:
<div ng-app="app" ng-controller="MainController as mainCtrl">
<canvas id="line" class="chart chart-line" chart-data="data"
chart-labels="labels" chart-series="series" chart-options="options"
chart-dataset-override="datasetOverride" chart-click="onClick">
</canvas>
</div>
Replace the handler of the global Chart:
Chart.defaults.global.legend.onClick = function (e, legendItem) {
var idx = legendItem.datasetIndex;
// IMPORTANT charts will be created in the second and third step
var chart = charts[e.srcElement.id];
chart.options.scales.yAxes[idx].display = !chart.options.scales.yAxes[idx].display;
var meta = chart.getDatasetMeta(idx);
// See controller.isDatasetVisible comment
meta.hidden = meta.hidden === null ? !chart.data.datasets[idx].hidden : null;
chart.update();
};
Create a global variable charts so we can get access each of the charts with the canvas id:
var charts = {};
Fill up the charts variables using the chart-create event:
angular.module("app", ["chart.js"]).controller("MainController", function ($scope) {
$scope.$on('chart-create', function (event, chart) {
charts[chart.chart.canvas.id] = chart;
});
$scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
$scope.series = ['Series A', 'Series B'];
$scope.data = [...
I wish there would be a better way of getting a chart from the canvas id, but as far as I know this is the suggested way by the developers.
This solution applies if you are using ng2-charts with chart.js and Angular 7^ and if you want to apply this behavior to all displayed charts.
import Chart from chart.js
Chart.defaults.global.legend.onClick = function (e: MouseEvent, chartLegendLabelItem: ChartLegendLabelItem) {
const idx: number = chartLegendLabelItem.datasetIndex;
const chart = this.chart;
chart.options.scales.yAxes[idx].display = !chart.options.scales.yAxes[idx].display;
const meta = chart.getDatasetMeta(idx);
meta.hidden = meta.hidden === null ? !chart.data.datasets[idx].hidden : null;
chart.update();
};
or for local configuration
legend: <ChartLegendOptions>{
onClick: function (e: MouseEvent, chartLegendLabelItem:ChartLegendLabelItem) {
const idx: number = chartLegendLabelItem.datasetIndex;
const chart = this.chart;
chart.options.scales.yAxes[idx].display =
!chart.options.scales.yAxes[idx].display;
const meta = chart.getDatasetMeta(idx);
meta.hidden = meta.hidden === null ?
!chart.data.datasets[idx].hidden : null;
chart.update();
}
}
I came along this problem using v3.8.0, none of the obove worked for me.
This code works for me.
Note I'm storing all my chart instances in a Map because I have multiple charts on the same page.
var instances = new Map();
When createing the incances I put them there.
and now the hiding of the y axis label and data on legend click:
onClick: function (event, legendItem) {
var instance = instances.get(event.chart.id);
var meta = instance.getDatasetMeta(legendItem.datasetIndex);
var newValue = !meta.yScale.options.display;
meta.hidden = meta.yScale.options.display;
meta.yScale.options.display = newValue;
instance.update();
}

Categories