ChartJS Separate Labels for each dataset/independent datasets? - javascript

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>

Related

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.

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

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.

Chart.JS: How to make sharp lines to smooth curved lines

Hi I'm new at charts and this is my chartjs chart, it's working currently, but it's showing in sharp lines and I want to make it smooth curve lines on this chart. Any ideas?
function statistics(data) {
if ($('#stats-currency').length > 0) {
if (typeof(stats_currency) !== 'undefined') {
stats_currency.destroy();
}
if (typeof(data) == 'undefined') {
var currency = $('select[name="currency"]').val();
$.get(admin_url + 'home/stats_currency/' + currency, function(response) {
stats_currency = new Chart($('#stats-currency'), {
type: 'line',
data: response,
options: {
responsive:true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
},
},
});
}, 'json');
} else {
stats_currency = new Chart($('#stats-currency'), {
type: 'line',
data: data,
options: {
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
},
},
});
}
This can be done through the option lineTension that needs to be defined on your dataset. Choose a value below 1.
datasets: [{
...
lineTension: 0.8
}]
By default, you should however already see curved smooth lines since accoring to Chart.js documentation, the default value is 0.4.
lineTension: Bezier curve tension of the line. Set to 0 to draw straight lines.
Please note that if the steppedLine value is set to anything other than false, lineTension will be ignored.
you can do it by adding tension value to your charts options
<canvas id="myChart"></canvas>
JS
const config = {
type: 'line', // your chart type
data: data, // pass here your data
options: {
elements: {
line: {
tension : 0.4 // smooth lines
},
},
},
};
// pass it like
const myChart = new Chart(
document.getElementById('myChart'),
config
);

bind first property value of an array of object into chart.js

I have an array of object and this is how I assigned values into it.
$("#gridview").click(function () {
$("table tbody th").each(function () {
var k = $(this).text().trim();
keys.push(k);
});
$("table tbody tr").each(function (i, el) {
var row = {}
$.each(keys, function (k, v) {
row[v] = $("td:eq(" + k + ")", el).text().trim();
});
myData.push(row);
});
myData.shift()
myData.length = 10
console.log(myData);
});
This is how my array of object looks like in inspect element - console
how can I get the values of Region and bind it to the labels below:
new Chart(document.getElementById("chart"), {
type: 'horizontalBar',
data: {
labels: [I want to display all the region here],
datasets: [{
label: "Android",
type: "horizontalBar",
stack: "Base",
backgroundColor: "#eece01",
data: ["I want to display ios user here"],
}, {
label: "ios",
type: "horizontalBar",
stack: "Base",
backgroundColor: "#87d84d",
data: ["I want to display android user here"]
}]
},
options: {
scales: {
xAxes: [{
//stacked: true,
stacked: true,
ticks: {
beginAtZero: true,
maxRotation: 0,
minRotation: 0
}
}],
yAxes: [{
stacked: true,
}]
},
}
});
FYI I have tried myData[Region] but its not working
Guys, I have searched the solutions whole day, seems cant found, please help
You can set the labels using .map() method on myData array like:
data: {
labels: myData.map(d => d.Region),
....
},
EDIT:
You can create a new function and add all chart init code into it like:
function CreateChart() {
new Chart(document.getElementById("chart"), {
type: 'horizontalBar',
data: {
labels: myData.map(d => d.Region),
... you code here
},
...
});
}
CreateChart();
and then on gridview click, again call this CreateChart function in the end like:
$("#gridview").click(function() {
// all your code logic here
console.log(myData);
CreateChart();
});

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