Chartjs show hidden data on tooltip - chart.js

Good Day,
I have a bar chart with multiple datasets for the chart. I would like to hide all the bars except for one (a Totals if you will), and on the Tooltip, I want to show all of the data in all the datasets. Unfortunately, the tooltip only shows the visible datasets. Does anyone know how to show all the data sets?
If you run this with
<canvas id="myChart" width="400" height="400"></canvas>
Hover over the chart and the first dataset (labeled 'First Label') is not shown. How do I show that in the tooltip? Does anyone know?
var ds1 = [], ds2 = [], ds3 = [], ds4 = [], ds5 = [], ds6 = [], labels = [];
for(var i = 0; i < 2; i++){
labels.push('Label: ' + i);
ds1.push(i);
ds2.push(i+1);
ds3.push(i+2);
ds4.push(i+3);
ds5.push(i+4);
ds6.push(i+5);
}
const dataSets = {
labels: labels,
datasets: [
{
label: 'First Label',
hidden: true,
data: ds1
},{
label: 'Second Label',
data: ds2
},{
label: 'Third Label',
data: ds3
},{
label: 'Fourth Label',
data: ds4
},{
label: 'Fifth Label',
data: ds5
},{
label: 'Totals',
data: ds6
}
]
}
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: dataSets,
elements: {
rectangle: {
borderWidth: 2
}
},
responsive: true,
legend: {
display: false
},
title: {
display: false
},
scales: {
yAxes: [
{
barThickness: 15
}
],
xAxes: [
{
ticks: {
suggestedMin: 0,
suggestedMax: 50
},
minBarLength: 5
}]
}
});
Thanks,
Tim

If you hide all bars except one, you can define a tooltips.callback function for label. This function collects the labels and appropriate values from all datasets using Array.map() and returns a string array.
tooltips: {
callbacks: {
label: (tooltipItem, chart) => dataSets.datasets.map(ds => ds.label + ': ' + ds.data[tooltipItem.index])
}
},
Please have a look at your amended code below:
var ds1 = [], ds2 = [], ds3 = [], ds4 = [], ds5 = [], ds6 = [], labels = [];
for (var i = 0; i < 2; i++) {
labels.push('Label: ' + i);
ds1.push(i);
ds2.push(i + 1);
ds3.push(i + 2);
ds4.push(i + 3);
ds5.push(i + 4);
ds6.push(5 * i + 10);
};
const dataSets = {
labels: labels,
datasets: [{
label: 'First Label',
hidden: true,
data: ds1
}, {
label: 'Second Label',
hidden: true,
data: ds2
}, {
label: 'Third Label',
hidden: true,
data: ds3
}, {
label: 'Fourth Label',
hidden: true,
data: ds4
}, {
label: 'Fifth Label',
hidden: true,
data: ds5
}, {
label: 'Totals',
data: ds6
}]
};
var myChart = new Chart('myChart', {
type: 'horizontalBar',
responsive: true,
data: dataSets,
elements: {
rectangle: {
borderWidth: 2
}
},
options: {
legend: {
display: false
},
title: {
display: false
},
tooltips: {
callbacks: {
label: (tooltipItem, chart) => dataSets.datasets.map(ds => ds.label + ': ' + ds.data[tooltipItem.index])
}
},
scales: {
xAxes: [{
ticks: {
min: 0,
stepSize: 1
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>
If you wanted to display the legend and allow users to show additional bars through a mouse click on individual legend labels, the callback function would be invoked once for each visible bar. Therefore you would have to make sure to return the labels array only once and return null in all other cases. The following code would return the labels array only for the 'Totals' bar.
tooltips: {
callbacks: {
label: (tooltipItem, chart) => {
if (tooltipItem.datasetIndex == dataSets.datasets.length - 1) {
return dataSets.datasets.map(ds => ds.label + ': ' + ds.data[tooltipItem.index]);
}
return null;
}
}
},
This would not work however, if the user decides to hide the 'Totals' bar. The code could however be improved to also overcome this limitation.

Related

Multiple bar charts side by side chartjs

I'm trying to create a bar chart that is grouped by the dataset rather than the label in chartjs3 and I'm having no luck. Before I switch over to building in D3, I wanted to check if this achievable within the confines of ChartJS.
Here is a link to a fiddle where I've been playing around with using different dataset structures and options from the Bar chart docs. I suspect that this is outside of the scope of the charting library, or is within the scope, but requires some custom components to be made – I would appreciate if anyone could direct me on what in particular I would need to extend (e.g. is it a case of a custom axes? or more?).
https://jsfiddle.net/f34ucs76/2/
const data = {
labels: [
'2000','2010','2020',
// 'Frogs','Monkeys','Squirrels','Bats'
],
datasets: [
{
label: 'Frogs',
data: [30.2,20.8,36.2],
backgroundColor: 'red',
//stack: 'Frogs',
},
{
label: 'Monkeys',
data: [16.3,13.0,22.3],
backgroundColor: 'blue',
//stack: 'Monkeys',
},
{
label: 'Squirrels',
data: [5.8,3.1,14.9],
backgroundColor: 'cyan',
//stack:'Squirrels',
},
{
label: 'Bats',
data: [0.1,3.6,2.6],
backgroundColor: 'aquamarine',
//stack:'Bats',
},
],
}
const options = {
maintainAspectRatio: false,
responsive: true,
interaction: {
intersect: false,
mode: 'index',
},
plugins: {
title: {
display: false,
},
subtitle: {
display: true,
align: 'start',
text: ['Source: Animals Index, June 2022'],
font: {
size: 12,
style: 'italic',
},
position: 'bottom',
padding: {
top: 20,
},
},
legend: {
display: true,
position: 'bottom',
},
tooltip: {
enabled: true,
},
},
scales: {
x: {
grid: {
display: false,
},
},
y: {
title: {
display: true,
text: 'Horsepower',
},
},
},
}
const mychart = new Chart(
document.getElementById('mychart'),
{
type: 'bar',
data: data,
options: options,
}
);
Your problem can be solved with Chart.js but the labels and the single dataset need to be generated.
Further you need to define your own legend by defining a plugins.legend.labels.generateLabels together with with a plugins.legend.labels.onClick function.
For further information, consult the Legend page from the Chart.js. documentation.
Please take a look at your amended and runnable code below and see how it works.
const baseData = {
labels: ['2000','2010','2020'],
datasets: [
{ label: 'Frogs', data: [30.2, 20.8, 36.2], bgColor: 'red', hidden: false },
{ label: 'Monkeys', data: [16.3, 13.0, 22.3], bgColor: 'blue', hidden: false },
{ label: 'Squirrels', data: [5.8,3.1, 14.9], bgColor: 'cyan', hidden: false },
{ label: 'Bats', data: [0.1, 3.6, 2.6], bgColor: 'aquamarine', hidden: false }
]
};
const iLastDs = baseData.datasets.length - 1;
const data = {
labels: baseData.datasets
.map(() => baseData.labels)
.map((labels, i) => i < iLastDs ? [...labels, null] : labels)
.flatMap(v => v),
datasets: [{
data: baseData.datasets
.map(ds => ds.data)
.map((data, i) => i < iLastDs ? [...data, null] : data)
.flatMap(v => v),
backgroundColor: baseData.datasets
.map(ds => ds.data.map(v => ds.bgColor))
.map((bgColors, i) => i < iLastDs ? [...bgColors, null] : bgColors)
.flatMap(v => v),
categoryPercentage: 1,
barPercentage: 0.9
}]
};
const options = {
maintainAspectRatio: true,
responsive: true,
interaction: {
intersect: true,
mode: 'index',
},
plugins: {
legend: {
position: 'bottom',
labels: {
generateLabels: chart => baseData.datasets.map((ds, i) => ({
datasetIndex: i,
text: ds.label,
fillStyle: ds.bgColor,
strokeStyle: 'lightgray',
hidden: baseData.datasets[i].hidden
}))
},
onClick: (event, legendItem, legend) => {
baseData.datasets[legendItem.datasetIndex].hidden = !baseData.datasets[legendItem.datasetIndex].hidden;
const iFirstValue = legendItem.datasetIndex + legendItem.datasetIndex * baseData.labels.length;
for (let i = iFirstValue; i < iFirstValue + baseData.labels.length; i++) {
legend.chart.toggleDataVisibility(i);
}
legend.chart.update();
}
},
tooltip: {
callbacks: {
title: ctx => {
const dsIndex = Math.floor(ctx[0].dataIndex / baseData.datasets.length);
return baseData.datasets[dsIndex].label + ' / ' + ctx[0].label;
}
}
}
},
scales: {
x: {
grid: {
display: false
}
},
y: {
title: {
display: true,
text: 'Horsepower',
}
}
}
};
new Chart('mychart', {
type: 'bar',
data,
options
});
span {
font-style: italic;
font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<canvas id="mychart" height="100"></canvas>
<span>Source: Animals Index, June 2022</span>

Chart js nested pie label colors in legend

I'm trying to have 2 pie charts and show in the legend only the inner labels.
The issues is that seems the labels color (in the legend) are taken from the the outer dataset, probably because it is the first.
How can I change it?
var ctx = $("#myChart");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['InnerLabel1','InnerLabebl2','InnerLabel3'],
datasets: [{
data: [1, 2, 1, 4],
backgroundColor: [
'rgba(31,119,180,0.5)','rgba(255,127,14,0.5)','rgba(255,127,14,0.5)','rgba(44,160,44,0.5)'
],
labels: [
'OuterLabel1','OuterLabel2','OuterLabel3','OuterLabel4'
]
}, {
data: [1, 3, 4],
backgroundColor: [
'#1f77b4','#ff7f0e','#2ca02c'
],
labels: ['InnerLabel1','InnerLabebl2','InnerLabel3'],
}, ]
},
options: {
responsive: true,
legend: {
display: true,
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ': ' + dataset.data[index];
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
<canvas id="myChart"></canvas>
You probably have to generate the legend labels yourself by defining a legend.labels.generateLabels function together with a legend.onClick that takes care of hiding and showing individual pie slices.
Here's an attempt of how this could be done.
const innerDataset = {
data: [1, 3, 4],
backgroundColor: ['#1f77b4', '#ff7f0e', '#2ca02c'],
labels: ['InnerLabel1', 'InnerLabebl2', 'InnerLabel3'],
};
var myChart = new Chart('myChart', {
type: 'pie',
data: {
datasets: [{
data: [1, 2, 1, 4],
backgroundColor: ['rgba(31,119,180,0.5)', 'rgba(255,127,14,0.5)', 'rgba(255,127,14,0.5)', 'rgba(44,160,44,0.5)'],
labels: ['OuterLabel1', 'OuterLabel2', 'OuterLabel3', 'OuterLabel4']
},
innerDataset
]
},
options: {
responsive: true,
legend: {
display: true,
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ': ' + dataset.data[index];
}
}
},
legend: {
labels: {
generateLabels: () => innerDataset.labels.map((label, i) => ({
text: label,
fillStyle: innerDataset.backgroundColor[i],
strokeStyle: '#fff',
hidden: myChart ? myChart.getDatasetMeta(1).data[i].hidden : false
}))
},
onClick: (event, legendItem) => {
const metaData = myChart.getDatasetMeta(1).data;
const iData = innerDataset.labels.indexOf(legendItem.text);
metaData[iData].hidden = !metaData[iData].hidden;
myChart.update();
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="myChart"></canvas>

How to put labels at 4 points of the day?

This question is two-fold (two ways to solve)
I want to make a chart that plots 24 hours worth of data, not starting at midnight, and with ticks (and associated grid) at the four cardinal points of the day.
I don't care if the x axis is 'time' or anything else, as long as it looks fine. I've seen a category chart with the labels arbitrarily shifted, but I can only reproduce this with one data point per label, and this needs multiple data points between the labels. If I label all the data points I don't know how to skip labels such that only "0:00', '6:00', '12:00', and '18:00' are visible.
It's supposed to look like this:
This is how far I've come:
function generateData() {
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
function randomPoint(date) {
return {
t: date.valueOf(),
y: randomNumber(0, 100)
};
}
var date = moment("2000-01-01T"+"08:30");
var now = moment();
var data = [];
while (data.length <=48) {
data.push(randomPoint(date));
date = date.clone().add(30, 'minute')
}
return data;
}
var cfg = {
data: {
datasets: [{
label: 'CHRT - Chart.js Corporation',
backgroundColor: 'red',
borderColor: 'red',
data: generateData(),
type: 'line',
pointRadius: 0,
fill: false,
lineTension: 0,
borderWidth: 2
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
round: 'minute',
unit: 'minute',
stepSize: 360,
displayFormats: {
minute: 'kk:mm'
}
}
}],
yAxes: [{
gridLines: {
drawBorder: false
}
}]
},
tooltips: {
intersect: false,
mode: 'index'
}
}
};
var chart = new Chart('chart1', cfg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart1" height="60"></canvas>
The problem here is that the first tick is at 08:30 not at 12:00.
I've tried to set the min value of the axis, but this either shifts part of the data out of view (min: moment("2000-01-01T12:00")), or creates a gap before the data starts (min: moment("2000-01-01T06:00")), both of which are unacceptable.
function generateData() {
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
function randomPoint(date) {
return {
t: date.valueOf(),
y: randomNumber(0, 100)
};
}
var date = moment("2000-01-01T"+"08:30");
var now = moment();
var data = [];
while (data.length <=48) {
data.push(randomPoint(date));
date = date.clone().add(30, 'minute')
}
return data;
}
var cfg = {
data: {
datasets: [{
label: 'CHRT - Chart.js Corporation',
backgroundColor: 'red',
borderColor: 'red',
data: generateData(),
type: 'line',
pointRadius: 0,
fill: false,
lineTension: 0,
borderWidth: 2
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
round: 'minute',
unit: 'minute',
stepSize: 360,
displayFormats: {
minute: 'kk:mm'
}
},
ticks: {
min: moment("2000-01-01T06:00"),
}
}],
yAxes: [{
gridLines: {
drawBorder: false
}
}]
},
tooltips: {
intersect: false,
mode: 'index'
}
}
};
var chart = new Chart('chart1', cfg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart1" height="60"></canvas>
Took me some time, but I think I got the answer.
You can define the ticks with and display them with options.scales.xAxes[0].ticks.source = 'labels', but the hardest part was to get the next timestamp of 0:00, 6:00, 12:00 or 18:00.
That's why the code for the first label is quite complex. If you want to know anything, just let me know and I can explain it.
Should work with any time you want.
Complete code (same as JSBin with preview here):
let data = {
datasets: [{
label: 'CHRT - Chart.js Corporation',
backgroundColor: 'red',
borderColor: 'red',
type: 'line',
pointRadius: 0,
pointHoverRadius: 0,
fill: false,
lineTension: 0,
borderWidth: 2,
data: []
}]
}
function randomNumber(min, max) {
return Math.round(Math.random() * (max - min) + min)
}
// temp variable for data.datasets[0].data
let datasetData = []
// Fill first dataset
datasetData[0] = {
x: moment("2000-01-01T08:30"),
y: randomNumber(0, 100)
}
// Fill remaining datasets
for (let i = 1; i < 48; i++) {
datasetData[i] = {
x: moment(datasetData[i-1].x).add(30, 'minutes'),
y: randomNumber(0, 100)
}
}
data.datasets[0].data = datasetData
// Fill first label
data.labels = [
moment(datasetData[0].x).hour(moment(datasetData[0].x).hour() + (6 - moment(datasetData[0].x).hour() % 6) % 6).minutes(0)
]
// Fill remaining labels
for (let i = 1; i < 4; i++) {
data.labels.push(moment(data.labels[i-1]).add(6, 'hours'))
}
let options = {
responsive: true,
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'hour',
displayFormats: {
hour: 'kk:mm'
}
},
ticks: {
source: 'labels'
}
}],
yAxes: [{
gridLines: {
drawBorder: false
}
}]
},
tooltips: {
intersect: false,
mode: 'index',
callbacks: {
title: function(tooltipItem, data) {
return moment(tooltipItem[0].label).format('YYYY-MM-DD, HH:mm')
}
}
}
}
let chart = new Chart('chart1', {
type: 'line',
data: data,
options: options
});

How to show different product name for every bar in chart js

I am using chart js for showing top 3 sold products in last week.
I want to show product name in tooltip for every bar which has obviously different products.
Here is my code :
function productChart() {
var data = {
labels: productHistoryDates,
datasets: [{
label: 'Product 1',
data: productHistoryProducts1,
backgroundColor: "#26B99A"
},
{
label: 'Product 2',
data: productHistoryProducts2,
backgroundColor: "#03586A",
},
{
label: 'Product 3',
data: productHistoryProducts3,
backgroundColor: "#03226A",
}]
};
var ctx = document.getElementById("productChart").getContext("2d");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
tooltips: {
enabled: true,
mode: 'single',
},
scales: {
yAxes: [{
gridLines: {
display: true
}
}],
xAxes: [{
gridLines: {
display: true
},
barPercentage: 0.8
}]
}
}
});
}
I am getting output like this.
But instead of product 1 label I want product name for that particular bar how can I achieve that ?
I solved it.
by passing an array to the label in data. And rest of the code is as below.
function productChart() {
var data = {
labels: productHistoryDates,
datasets: [{
label: productHistoryProducts1.name,
data: productHistoryProducts1.quantity,
backgroundColor: "#26B99A"
},
{
label: productHistoryProducts2.name,
data: productHistoryProducts2.quantity,
backgroundColor: "#03586A",
},
{
label: productHistoryProducts3.name,
data: productHistoryProducts3.quantity,
backgroundColor: "#03226A",
}]
};
var ctx = document.getElementById("productChart").getContext("2d");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function (tooltipItems, data) {
var tooltip = data.datasets[tooltipItems.datasetIndex].label[tooltipItems.index];
return tooltip;
}
}
},
scales: {
yAxes: [{
gridLines: {
display: true
}
}],
xAxes: [{
gridLines: {
display: true
},
ticks: { mirror: true },
barPercentage: 0.8
}]
}
}
});
}

Chart.js - displaying multiple line charts using multiple labels

I need to draw a chart with 2 lines using Chart.js.
Each of this line has a different label set.
i.e.
Chart 1:
1 -> 2
2 -> 4
3 -> 8
4 -> 16
Chart 2:
1 -> 3
3 -> 4
4 -> 6
6 -> 9
This following sample obviously does not work as it uses the labels from chart1. But is it possible to realize this with Chart.js?
var config = {
type: 'line',
data: {
labels: [1,2,3,4,5],
datasets: [{
label: 'Chart 1',
data: [2,4,8,16],
}, {
label: 'Chart 2',
data: [3,4,6,9],
}]
},
Other charting libs offers a (label/data) set as parameter so I could simply give a tupel as parameter
(ie. [(1->2),(2->4),(3->8)...]
for each chart and the lib will match everything.
Thanks
Edit: Detailed sample as requested:
var config = {
type: 'line',
data: {
labels: [1, 2, 3, 4, 5],
datasets: [{
label: 'Chart 1',
data: [2, 4, 8, 16],
}, {
label: 'Chart 2',
data: [3, 4, 6, 9],
}]
},
options: {
spanGaps: true,
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart'
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Labels'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Values'
},
ticks: {
min: 1,
max: 10,
}
}]
}
}
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<div style="width:90%;" class="container">
<canvas id="canvas"></canvas><br>
</div>
Use scatter type chart and showLine: true instead of line type with labels:
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [
{
label: 'Chart 1',
data: [{x: 1, y: 2}, {x: 2, y: 4}, {x: 3, y: 8},{x: 4, y: 16}],
showLine: true,
fill: false,
borderColor: 'rgba(0, 200, 0, 1)'
},
{
label: 'Chart 2',
data: [{x: 1, y: 3}, {x: 3, y: 4}, {x: 4, y: 6}, {x: 6, y: 9}],
showLine: true,
fill: false,
borderColor: 'rgba(200, 0, 0, 1)'
}
]
},
options: {
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart"></canvas>
What this code does is, it displays multi line graph using chart.js
Create a class for your labeling x and y values
//DataContract for Serializing Data - required to serve in JSON format
[DataContract]
public class LabelPoint
{
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "label")]
public string Label { get; set; }
public DataPoint DataPoint { get; set; }
}
[DataContract]
public class DataPoint
{
[DataMember(Name = "x")]
public List<string> X { get; set; }
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "y")]
public List<string> Y { get; set; }
}
Controller code to retrieve data
List<LabelPoint> dataPoints = GetProducts.ToList()
.GroupBy(p => p.ProductName,
(k, c) => new LabelPoint()
{
DataPoint = new DataPoint { X = c.Select(y => y.Date.ToString("dd/MM/yyyy HH:mm")).ToList(), Y = c.Select(cs => cs.Quantity).ToList() },
Label = k
}
).ToList();
ViewBag.DataPoints = dataPoints;
cshtml code to display chart and retrieve data
<canvas id="myChart"></canvas>
<script>
$(document).ready(function () {
// Get the data from the controller using viewbag
// so the data looks something like this [ { Label : "ABC" , DataPoint :[ { X: '222' , Y :60 } ] } ]
var data = #Html.Raw(Json.Encode(ViewBag.DataPoints));
// declare empty array
var dataSet = []; var qty= []; var dates= [];
// loop through the data and get the Label as well as get the created dates and qty for the array of object
for (var i = 0; i < data.length; i++) {
qty.push(data[i].DataPoint.Y);
for (var d = 0; d < data[i].DataPoint.X.length; d++) {
// we're setting this on the X- axis as the label so we need to make sure that we get all the dates between searched dates
dates.push(data[i].DataPoint.X[d]);
}
// we create an array of object, set the Lable which will display LocationName, The data here is the Quantity
dataSet.push(
{
label: data[i].Label,
data: data[i].DataPoint.Y,
fill: false,
borderColor: poolColors(qtyInLocations.length),
pointBorderColor: "black",
pointBackgroundColor: "white",
lineTension: 0.1
}
);
}
// this is the options to set the Actual label like Date And Quantity
var options = {
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: "Date",
fontSize: 20
},
}],
yAxes: [{
ticks: {
beginAtZero:true
},
scaleLabel: {
display: true,
labelString: 'Quantity',
fontSize: 20
}
}]
}
};
// we need to remove all duplicate values from the CreatedDate array
var uniq = [ ...new Set(dates) ];
// get the canvas
var ctx = document.getElementById("myChart").getContext('2d');
// build the chart
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: uniq,
datasets:dataSet
},
options: options
});
});
/// will get get random colors each time
function dynamicColors() {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgba(" + r + "," + g + "," + b + ", 0.5)";
}
/// will display random colors each time
function poolColors(a) {
var pool = [];
for(i = 0; i < a; i++) {
pool.push(dynamicColors());
}
return pool;
}
</script>