Chart.js multicolored fill sections - javascript

I have a chart which contains blue or green data points depending on the value of a point.
Is it possible to change the fill color beneath these points to reflect their value as well?
Similar to this codepen https://codepen.io/jordanwillis/pen/BWxErp using a gradient of colors switching between them under each data point.
Below is my chart switching between colored datapoints.
var chartColors = {
blue: 'rgb(54, 162, 235)',
green: 'rgb(75, 192, 192)'
}
// x-axis labels
var chartData = {
labels: ['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018', '5/1/2018', '6/1/2018', '7/1/2018'],
datasets: [
{label: 'Light',
fill: true,
borderColor: window.chartColors.blue,
pointBackgroundColor: [],
pointBorderColor: [],
pointRadius: 10,
pointHoverRadius: 10,
data: data1},
]
};
window.onload = function() {
var config = document.getElementById("canvas").getContext("2d");
window.myLine = Chart.Line(config, {
type: "line",
data: chartData,
options: {
responsive: true,
title: {
display: true,
text: ['Light Intensity'],
fontSize: 14
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Date (3 day intervals)'
},
type: 'linear',
position: 'bottom',
ticks: {
max: 59,
min: 0,
stepSize: 10,
callback: function(value, index, values) {
return chartData.labels[index];
}
}
}],
yAxes: [{
display: true,
ticks:{min: 0, max: 400, reverse: false},
scaleLabel: {
display: true,
labelString: 'Photosynthetically Available Radiation'
}
}]
}
}
});
};
// change colors of points here
function algeaFill(respiration, depth){
var dataPoints = [];
lightAvgs = [65.3, 33.14, 22.01, 34.74, 26.58, 38.49, 48.12, 44.3, 28.55, 28.92, 37.21, 38.13, 42.49, 44.65, 80.62, 104.66, 87.16, 72.72, 91.07, 93.89, 113.01, 109.56, 110.08, 126.43, 128.98,
165.52, 196.73, 156.93, 140.41, 130.24, 164.14, 150.28, 127.09, 134.54, 129.89, 115.30, 181.71, 259.52, 269.57, 241.86, 221.29, 212.84, 246, 271.05, 238.03, 250.05, 256.02, 236.56, 259.93,
286.6, 283.94, 298.4, 279.81, 256.37, 262.98, 236.18, 305.79, 318.73, 289.67, 277.52];
for(var i = 0; i < 60; i++){
if(lightAvgs[i] <= depth){
window.myLine.data.datasets[0].pointBackgroundColor[i] = "green";
}else{
window.myLine.data.datasets[0].pointBackgroundColor[i] = "blue";
}
dataPoints.push({x: i, y: lightAvgs[i]});
}
return dataPoints;
}
// call algeaFill
window.myLine.data.datasets[0].data = algeaFill(respirationSlider.value, depthSlider.value);
window.myLine.update();
});

in each dataset object insert backgroundColor and pointBackgroundColor properties.
backgroundColor: 'rgb(54, 162, 235)',
pointBackgroundColor: 'rgb(54, 162, 235)'

Related

Prevent chart.js "jumping"

From question ChartJS: How to set fixed Y axis max and min I'm attempting to limit the y axis values using:
ticks : {
max : 200,
min : -200
}
This is in order to prevent the charing "jumping" on incoming data to match the y-axis values range. If there is an alternative to prevent the data jumping please suggest, I assume setting max and min y values will prevent the chart "jumping" as the range is set to a static, rather than dynamic value.
fiddle: https://jsfiddle.net/adrianfiddleuser/yd4mfubp/10/
HTML:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://github.com/nagix/chartjs-plugin-streaming/releases/download/v1.5.0/chartjs-plugin-streaming.min.js"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<p>
<button id="randomizeData">Randomize Data</button>
<button id="addDataset">Add Dataset</button>
<button id="removeDataset">Remove Dataset</button>
<button id="addData">Add Data</button>
<span class="label">pause:</span>
<span><input type="checkbox" id="pause" class="control"></span>
</p>
</body>
javascript:
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
function randomScalingFactor() {
return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
}
function onRefresh(chart) {
chart.config.data.datasets.forEach(function(dataset) {
dataset.data.push({
x: Date.now(),
y: randomScalingFactor()
});
});
}
var color = Chart.helpers.color;
var config = {
type: 'line',
data: {
datasets: [{
label: 'Dataset 1 (linear interpolation)',
backgroundColor: color(chartColors.red).alpha(0.5).rgbString(),
borderColor: chartColors.red,
fill: false,
lineTension: 0,
borderDash: [8, 4],
data: []
}, {
label: 'Dataset 2 (cubic interpolation)',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: chartColors.blue,
fill: false,
cubicInterpolationMode: 'monotone',
data: []
}]
},
options: {
title: {
display: true,
text: 'Line chart (hotizontal scroll) sample'
},
scales: {
xAxes: [{
type: 'realtime'
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value',
ticks : {
max : 200,
min : -200
}
}
}]
},
tooltips: {
mode: 'nearest',
intersect: false
},
hover: {
mode: 'nearest',
intersect: false
},
plugins: {
streaming: {
duration: 20000,
refresh: 1000,
delay: 2000,
onRefresh: onRefresh
}
}
}
};
//window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
window.myChart = new Chart(ctx, config);
//};
document.getElementById('randomizeData').addEventListener('click', function() {
config.data.datasets.forEach(function(dataset) {
dataset.data.forEach(function(dataObj) {
dataObj.y = randomScalingFactor();
});
});
window.myChart.update();
});
var colorNames = Object.keys(chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[config.data.datasets.length % colorNames.length];
var newColor = chartColors[colorName];
var newDataset = {
label: 'Dataset ' + (config.data.datasets.length + 1),
backgroundColor: color(newColor).alpha(0.5).rgbString(),
borderColor: newColor,
fill: false,
lineTension: 0,
data: []
};
config.data.datasets.push(newDataset);
window.myChart.update();
});
document.getElementById('removeDataset').addEventListener('click', function() {
config.data.datasets.pop();
window.myChart.update();
});
document.getElementById('addData').addEventListener('click', function() {
onRefresh(window.myChart);
window.myChart.update();
})
Setting the max and min y-axis values does not appear to fix the issue. How to prevent the chart from "jumping" on incoming data?
Your attempt with defining ticks.min and ticks.max is fine. The only problem is that you defined ticks at the wrong place. Change it as follows and it will work as expected.
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value',
},
ticks: {
max: 100,
min: -100
}
}]
Please have a look at your amended JSFiddle.

Why using logarithmic gives 8e+2 value?

I am using a chart and I am using type: 'logarithmic', passing the max value like this:
max: scalesMax.toFixed(2),
But that gives me 8e+2
How can I fix it?
I'm using chart.js
This how I get my values for each charts, I have one chart next to the other to compare each values form 2 datasets
var scalesMaxTotalCasesTrend = Math.max(...customConfirmed);
var scalesMaxTotalPositiveTrend = Math.max(...totPositivi);
var scalesMaxIsolationTrend = Math.max(...totIsolamento);
var scalesMaxHospitalizationTrend = Math.max(...totRicoverati);
var scalesMaxHospitalizationWithSymptomsTrend = Math.max(...totRicoveratiConSintomi);
var scalesMaxIntensiveCareTrend = Math.max(...totTerapiaIntensiva);
function setConfigurationGraph(dataGraphType, labels, data, scalesMax) {
configAllDateGraph.push({
dataGraphType: dataGraphType,
type: 'line',
data: {
labels: labels,
datasets: [{
fill: true,
backgroundColor: "rgba(250, 250, 250, 1)",
data: data,
borderColor: "#fafafa",
borderDash: [5, 5],
backgroundColor: "#fafafa",
pointBackgroundColor: "#fafafa",
pointBorderColor: "#fafafa",
pointHoverBackgroundColor: "#fafafa",
pointHoverBorderColor: "#fafafa"
}]
},
options: {
responsive: true,
title: {
display: true
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
gridLines: {
color: "#fafafa"
},
ticks: {
fontColor: "#fafafa"
}
}],
yAxes: [{
display: true,
type: 'logarithmic',
gridLines: {
color: "#fafafa"
},
ticks: {
fontColor: "#fafafa",
beginAtZero: true,
max: scalesMax.toFixed(2),
min: 0
}
}]
},
legend: {
display: false
}
}
});
}
This automatically happens in JS i believe.
You can use toFixed() max limit of 20;
Have you tried this
max: scalesMax.toFixed(20)

How to setup or show all tool-tip text by default without hover

I am working on one project where i am using Charts.js for showing charts, Here i want to show all bar values by default on top of each bar (Using bar chat), when we hover mouse on that bar it shows value, but is there any was to show that tooltip by default without hover on it
Below fiddle is the example, Here in this fiddle i want to show 60,30,40 as default on bar chart by default without taking hover on it.
Here in above screenshot i have tried to put all the tooltip as by default but as there are 3 charts are used it shows tooltip to all the charts but I want to put tooltip to only bar chart, I know it's bit tricky but there will be some way using which i can resolve my issue.
Please guide me, here is my code snipped of JS
getchart();
function getchart() {
$("#barChart").remove();
const decimals = 3;
$(".chart").append("<canvas id='barChart' width='692' height='346'></canvas>");
var ctx = document.getElementById("barChart");
Chart.pluginService.register({
beforeRender: function(chart) {
if (chart.config.options.showAllTooltips) {
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function(dataset, i) {
chart.getDatasetMeta(i).data.forEach(function(sector, j) {
console.log(chart);
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
}
chart.options.tooltips.enabled = false;
},
afterDraw: function(chart, easing) {
if (chart.config.options.showAllTooltips) {
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
tooltip.initialize();
tooltip.update();
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
})
var barChart;
barChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['30', '45', '60', '90', '120', '120+'],
datasets: [{
type: 'bar',
label: 'Receivable',
data: [730, 492.5, 120, 4732.5, 2760.85, 0],
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}, {
type: 'line',
label: 'Past Due',
data: [1500, 1500, 1500, 1500, 1500, 1500],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}, {
type: 'line',
label: 'Invoice',
data: [1000, 1000, 1000, 1000, 1000, 1000],
backgroundColor: 'rgba(75, 00, 150, 0.2)',
borderColor: 'rgba(75, 00, 150,1)',
borderWidth: 2
}]
},
options: {
scales: {
xAxes: [{
display: true,
stacked: true,
scaleLabel: {
display: true,
labelString: 'Days'
},
}],
yAxes: [{
display: true,
stacked: true,
scaleLabel: {
display: true,
labelString: 'Dollar Amount'
},
ticks: {
beginAtZero: true,
}
}, {
id: 'invoice-amount',
display: false,
stacked: false,
scaleLabel: {
display: false,
labelString: 'Dollar Amount'
},
ticks: {
beginAtZero: true,
}
}]
},
showAllTooltips: true,
}
});
}

How to show/hide animation when legend clicked chart js

i add animation to show label value data on value points in line chart js. but when i click the legend to hide a line, the label not disappear. to be honest, i really don't have any clue to fix it.
the chart now
the chart after hide some line with legend
var ctxTotal = $("#grap_trajec_divisi");
var chartOptions = {
responsive: true,
maintainAspectRatio: false,
legend: {
position: 'bottom',
},
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function (tooltipItems, data) {
var dataM = tooltipItems.yLabel;
formatM(dataM);
var multistringText = [data_M];
multistringText.push(tooltipItems.yLabel);
multistringText.push(data.datasets[tooltipItems.datasetIndex].label);
return multistringText;
}
}
},
scales: {
xAxes: [{
display: true,
gridLines: {
color: "#f3f3f3",
drawTicks: true,
},
scaleLabel: {
display: false,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
gridLines: {
color: "#f3f3f3",
drawTicks: true,
},
scaleLabel: {
display: false,
labelString: 'Value'
},
ticks: {
callback: function (value, index, values) {
var dataYaxis = value;
formatM(dataYaxis);
return data_M;
}
},
}]
},
animation: {
duration: 1,
onComplete: function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = '.7rem "Calibri",sans-serif';
ctx.fillStyle = '#555';
ctx.textAlign = "center";
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
formatM(data);
ctx.fillText(data_M, bar._model.x, bar._model.y - 5);
});
});
}
}
//title: {
// display: true,
// text: 'Chart.js Line Chart - proyeksi'
//}
};
var chartData = {
labels: arr,
datasets: [{
label: "RKAP",
data: value_LT,
fill: false,
borderColor: "rgb(89,159,240)",
pointBorderColor: "rgb(89,159,240)",
pointBackgroundColor: "#FFFFFF",
pointBorderWidth: 1,
pointHoverBorderWidth: 1,
pointRadius: 3,
spanGaps: true,
}, {
label: "Target",
data: value_LT2,
fill: false,
borderColor: "rgb(186,179,61)",
pointBorderColor: "rgb(186,179,61)",
pointBackgroundColor: "#FFFFFF",
pointBorderWidth: 1,
pointHoverBorderWidth: 1,
pointRadius: 3,
spanGaps: true,
}, {
label: "Actual",
data: value_LO,
fill: false,
borderColor: "rgb(78,199,138)",
pointBorderColor: "rgb(78,199,138)",
pointBackgroundColor: "#FFFFFF",
pointBorderWidth: 1,
pointHoverBorderWidth: 1,
pointRadius: 3,
spanGaps: true,
}, {
label: "Proyeksi",
data: value_LP,
fill: false,
borderColor: "rgb(241,151,89)",
pointBorderColor: "rgb(241,151,89)",
pointBackgroundColor: "#FFFFFF",
pointBorderWidth: 1,
pointHoverBorderWidth: 1,
pointRadius: 3,
spanGaps: true,
}],
};
var config = {
type: 'line',
options: chartOptions,
data: chartData
};
if (window.chartTrajecDivisi != undefined) {
window.chartTrajecDivisi.destroy();
}
window.chartTrajecDivisi = new Chart(ctxTotal, config);
i want to hide the label when line hide by clicking the label, so the label and the line is hide / show together.
I think this works.
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
if (!meta.hidden) {
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
formatM(data);
ctx.fillText(data_M, bar._model.x, bar._model.y - 5);
});
}
});
i found the answer for this. just remove the animation, and used plugin datalabel chart js.

Display values in Pareto chart using Chart.js 2.0.2

I have a Pareto chart (using Chart.js Version: 2.0.2) and i need to display values inside of the bars and under the line.
Any help will be very appreciated:
This is the code (hope that it is useful for somebody):
<canvas id="canvas"></canvas>
<script type="text/javascript">
var data = {
labels: ["8","7","9","11","10"],
datasets: [{
type: "line",
label: "Acumulado",
borderColor: "#BA1E14",
backgroundColor: "#BA1E14",
pointBorderWidth: 5,
fill: false,
data: [34.04,57.45,76.60,89.36,100.00],
yAxisID: 'y-axis-2'
},{
type: "bar",
label: "Asistencia",
borderColor: "#56B513",
backgroundColor: "#56B513",
data: [16,11,9,6,5],
yAxisID: 'y-axis-1'
},{
type: "bar",
label: "SoluciĆ³n",
borderColor: "#000FAA",
backgroundColor: "#000FAA",
data: [16,11,9,6,5],
yAxisID: 'y-axis-1'
}]
};
var options = {
scales: {
xAxes: [{
stacked: true,
scaleLabel: {
display: true,
labelString: "Estaciones"
}
}],
yAxes: [{
type: "linear",
position: "left",
id: "y-axis-1",
stacked: true,
ticks: {
suggestedMin: 0
},
scaleLabel: {
display: true,
labelString: "Minutos"
}
},{
type: "linear",
position: "right",
id: "y-axis-2",
ticks: {
suggestedMin: 0,
callback: function(value) {
return value + "%";
}
},
scaleLabel: {
display: true,
labelString: "Porcentaje"
}
}]
}
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
};
</script>
Right now the chart looks like this:
And i need it to look like this:
This is the answer i developed (only in the options object):
var options = {
animation: {
onComplete: function() {
var ctx = this.chart.ctx;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
this.chart.config.data.datasets.forEach(function(dataset) {
ctx.font = "20px Arial";
switch (dataset.type) {
case "line":
ctx.fillStyle = "Black";
dataset.metaData.forEach(function(p) {
ctx.fillText(p._chart.config.data.datasets[p._datasetIndex].data[p._index], p._model.x, p._model.y - 20);
});
break;
case "bar":
ctx.fillStyle = "White";
dataset.metaData.forEach(function(p) {
ctx.fillText(p._chart.config.data.datasets[p._datasetIndex].data[p._index], p._model.x, p._model.y + 20);
});
break;
}
});
}
}
...
};
And this is the result:
I think since version 2.6.0 it's possible to Mix ChartTypes, like Bars and Lines
follow the instructions
A short example is 2 DataSet, one is bar type and other line type:
const data = {
labels: [
'January',
'February',
'March',
'April'
],
datasets: [{
type: 'bar',
label: 'Bar Dataset',
data: [10, 20, 30, 40],
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(255, 99, 132, 0.2)'
}, {
type: 'line',
label: 'Line Dataset',
data: [50, 50, 50, 50],
fill: false,
borderColor: 'rgb(54, 162, 235)'
}]
};
You just have to calculate the Pareto values and put on the Dataset Line Type

Categories

Resources