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>
Related
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>
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
});
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.
I'm trying to recreate this below chart with a stacked option on my background lines
But my attempts were unsuccessful with this image below as result
$(function() {
var areaChartCanvas = $('#areaChart').get(0).getContext('2d')
var areaChartData = {
labels: ['', '', ''],
datasets: [{
backgroundColor: 'transparent',
borderColor: 'black',
pointRadius: false,
data: [32, 12, 28],
type: 'line'
}, {
backgroundColor: 'red',
pointRadius: false,
data: [20, 20, 20]
}, {
backgroundColor: 'orange',
pointRadius: false,
data: [40, 40, 40]
}, {
backgroundColor: 'cyan',
pointRadius: false,
data: [60, 60, 60]
}]
}
var areaChartOptions = {
maintainAspectRatio: false,
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
display: true,
}
}],
yAxes: [{
gridLines: {
display: true,
},
stacked: true
}]
}
}
var areaChart = new Chart(areaChartCanvas, {
type: 'line',
data: areaChartData,
options: areaChartOptions
})
})
<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.8.0/Chart.min.js"></script>
<canvas id="areaChart" style="height:250px"></canvas>
ideally, I want to be able to create 'AREAS' with different colors that will be stacked according to the interval I pass to it.
e.g:
cyan - 20
orange - 20
red - 20
but currently, I'm doing
cyan - 60
orange - 40
red - 20
If I understand you correctly, I thought about different approach and extends the chart with Plugin[1] (Inspired by https://stackoverflow.com/a/49303362/863110)
Chart.pluginService.register({
beforeDraw: function (chart, easing) {
if (chart.config.options.fillColor) {
var ctx = chart.chart.ctx;
var chartArea = chart.chartArea;
ctx.save();
let delta = 0;
const chartHeight = chartArea.bottom - chartArea.top;
const bottomBarHeight = chart.height - chartHeight - chartArea.top;
chart.config.options.fillColor.map(color => {
const colorHeight = chartHeight * (color[0] / 100);
const colorBottom = chartArea.bottom + colorHeight;
ctx.fillStyle = color[1];
const x = chartArea.left,
y = chart.height - bottomBarHeight - colorHeight - delta,
width = chartArea.right - chartArea.left,
height = colorHeight;
delta += height;
ctx.fillRect(x, y, width, height);
ctx.restore();
})
}
}
});
var chartData = {
labels: ['a', 'b', 'c', 'd'],
datasets: [{
label: 'value',
borderColor: 'blue',
data: [30, 50, 25, 10]
}]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myBar = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
scales: {
yAxes: [{ ticks: { max: 60 } }]
},
legend: { display: false },
fillColor: [
[20, 'red'],
[20, 'blue'],
[20, 'green'],
[20, 'pink'],
[20, 'yellow'],
]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart" height="300" width="500"></canvas>
https://jsbin.com/lisuvuq/2/edit?js,output
[1] - With Plugin you can custom the chart's behaviour. When you use Plugin you get an API so you can "listen" to life cycle events of the chart (beforeDraw for example) and call your own code. The API calls your function and gives you data about the chart so you can use it in your code.In this example, we're using the API to (1) Run a code before the chart been drawing (2) Using the data to calculate the areas of the different colors. (3) Draw additional shapes (ctx.fillRect) based on the calculation.
I saw your post regarding,
Instead of just "Stock" at the left, is there anyway to put a separate label for each bar, eg 18, 82, 22, 80 going down the y-axis?
Below is the link which I'm referring ...
ChartJS bar chart with legend which corresponds to each bar
You are looking for something like the following:
var chart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: [18, 82, 22, 80],
datasets: [{
data: [1, 2, 3, 4],
backgroundColor: ['#ff6384', '#36a2eb', '#ffce56', '#4bc0c0', '#9966ff'],
borderColor: ['#ff6384', '#36a2eb', '#ffce56', '#4bc0c0', '#9966ff']
}]
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
labels: {
generateLabels: function(chart) {
var labels = chart.data.labels;
var dataset = chart.data.datasets[0];
var legend = labels.map(function(label, index) {
return {
datasetIndex: 0,
text: label,
fillStyle: dataset.backgroundColor[index],
strokeStyle: dataset.borderColor[index],
lineWidth: 1
}
});
return legend;
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>