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.
Related
As title says Im looking to put 2 or more charts on the same page, but everytime I put the 2nd, the first chart dissapears. What is the correct method to add 2 or more charts?
<!doctype html>
<html>
<head>
<title>Twin</title>
<script src="https://cdn.jsdelivr.net/npm/moment#2.24.0/min/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/hammerjs#2.0.8"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom#0.7.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-streaming#1.8.0"></script>
</head>
<style>
#myChart1 {
position: relative;
left: 25%;
top: 25%;
}
#myChart2 {
position: relative;
left: 55%;
top: 25%;
}
</style>
<!--Charts-->
<body>
<div style="position: relative; height:100px; width:500px">
<canvas id="myChart1" style="border: 1px solid #ccc"></canvas>
</div>
<div style="position: relative; height:100px; width:500px">
<canvas id="myChart2" style="border: 1px solid #ccc"></canvas>
</div>
</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>
<button id="resetZoom">Reset Zoom</button> -->
</p>
</body>
<!--1-->
<script>
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: 'Schwingwert',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: chartColors.blue,
fill: false,
cubicInterpolationMode: 'monotone',
data: []
}]
},
options: {
legend: {
position: 'top'
},
title: {
display: true,
text: 'X Axis Zeitstempel (ms) / Y Axis Schwingungswert (m/sec)',
position: 'top'
},
scales: {
xAxes: [{
type: 'realtime',
scaleLabel:{
display: true,
labelString: 'Zeitstempel (ms)'
},
realtime: {
duration: 20000,
refresh: 1000,
delay: 2000,
onRefresh: onRefresh,
}
}],
yAxes: [{
type: 'linear',
display: true,
scaleLabel: {
display: true,
labelString: 'Amplitude (m/sec)'
}
}]
},
tooltips: {
mode: 'nearest',
intersect: false
},
hover: {
mode: 'nearest',
intersect: false
},
pan: {
enabled: true,
mode: 'x',
rangeMax: {
x: 4000
},
rangeMin: {
x: 0
}
},
zoom: {
enabled: true,
mode: 'x',
rangeMax: {
x: 20000
},
rangeMin: {
x: 1000
}
}
}
};
window.onload = function() {
var ctx1 = document.getElementById('myChart1').getContext('2d');
window.myChart = new Chart(ctx1, 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();
});
document.getElementById('resetZoom').addEventListener('click', function() {
window.myChart.resetZoom();
});
</script>
<!--2-->
<script>
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: 'Schwingwert',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: chartColors.blue,
fill: false,
cubicInterpolationMode: 'monotone',
data: []
}]
},
options: {
legend: {
position: 'top'
},
title: {
display: true,
text: 'X Axis Zeitstempel (ms) / Y Axis Schwingungswert (m/sec)',
position: 'top'
},
scales: {
xAxes: [{
type: 'realtime',
scaleLabel:{
display: true,
labelString: 'Zeitstempel (ms)'
},
realtime: {
duration: 20000,
refresh: 1000,
delay: 2000,
onRefresh: onRefresh,
}
}],
yAxes: [{
type: 'linear',
display: true,
scaleLabel: {
display: true,
labelString: 'Amplitude (m/sec)'
}
}]
},
tooltips: {
mode: 'nearest',
intersect: false
},
hover: {
mode: 'nearest',
intersect: false
},
pan: {
enabled: true,
mode: 'x',
rangeMax: {
x: 4000
},
rangeMin: {
x: 0
}
},
zoom: {
enabled: true,
mode: 'x',
rangeMax: {
x: 20000
},
rangeMin: {
x: 1000
}
}
}
};
window.onload = function() {
var ctx2 = document.getElementById('myChart2').getContext('2d');
window.myChart = new Chart(ctx2, 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();
});
document.getElementById('resetZoom').addEventListener('click', function() {
window.myChart.resetZoom();
});
</script>
</body>
</html>
Do any of you have any ideas? possibly I am not on the right track!
I tried with different id attributes, but it doesn't work so far!
Your two JavaScript blocks are almost same( same config, same functions, etc...), I refactor to clarify.
Look for my working example: Chart.js multiple charts in same page
Initialize the charts:
...
function onLoadOverride(chartId, config) {
var ctx1 = document.getElementById(chartId).getContext("2d");
new Chart(ctx1, config);
}
onLoadOverride("myChart1", config);
onLoadOverride("myChart2", config);
...
Using below code I'm attempting to pause chart.js horizontal scroll:
config.options.scales.xAxes[0].realtime.pause = this.checked;
But it appears the pause is not being registered, when I click the checkbox "pause" the horizontal scroll continues.
Based on question Pause horizontal scrolling in chart.js for real time data they same fix does not apply here.
Fiddle : https://jsfiddle.net/adrianfiddleuser/yd4mfubp/6/
src:
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 id="pauseValue" class="value">false</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'
}
}]
},
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();
})
document.getElementById('pause').addEventListener('click', function() {
config.options.scales.xAxes[0].realtime.pause = this.checked;
window.myChart.update({duration: 0});
document.getElementById('pauseValue').innerHTML = this.checked;
window.myChart.update();
})
You need to access the property of the actual chart, instead of updating the config.
Try changing config.options.scales.xAxes[0].realtime.pause = this.checked; to window.myChart.chart.options.plugins.streaming.pause = this.checked; in the pause checkbox's click listener.
document.getElementById('pause').addEventListener('click', function() {
window.myChart.chart.options.plugins.streaming.pause = this.checked;
window.myChart.update({duration: 0});
document.getElementById('pauseValue').innerHTML = this.checked;
window.myChart.update();
})
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)'
I'm a bit stuck on adding conditional background colours to a row in ChartJS, based on numbers on the vertical axis.
Eg.
If the vertical axis is between 0 - 6, background colour for those rows is green.
If the vertical axis is between 6 - 12 background colour for those rows is grey
If the vertical axis is > 12 background colour for those rows is red
Has anyone done something like this before?
I've attached a picture that roughly describes the functionality.
Cheers!
There is no option to do this with chartjs. However you can write your own plugin and draw the background by yourself in the beforeDraw hook for example.
var chart = new Chart(ctx, {
plugins: [{
beforeDraw: function(chart) {
//..
}
}]
});
You can get all the information to calculate the height of an y-axis-segment from the chart parameter.
I've included a snippet below how this could be implemented. Note however that this is more a proof of concept than a proper implementation:
var canvas = document.getElementById('myChart');
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(51, 204, 51)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var myLineChart = new Chart(canvas,
{
type: 'line',
data: {
labels: ['1', '2', '3', '4', '5'],
datasets: [
{
label: '# of Votes',
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [2, 5, 12.5, 9, 6.3]
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Conditional Background'
},
backgroundRules: [{
backgroundColor: window.chartColors.green,
yAxisSegement: 6
}, {
backgroundColor: window.chartColors.grey,
yAxisSegement: 12
}, {
backgroundColor: window.chartColors.red,
yAxisSegement: Infinity
}],
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
},
plugins: [{
beforeDraw: function (chart) {
var ctx = chart.chart.ctx;
var ruleIndex = 0;
var rules = chart.chart.options.backgroundRules;
var yaxis = chart.chart.scales["y-axis-0"];
var xaxis = chart.chart.scales["x-axis-0"];
var partPercentage = 1 / (yaxis.ticksAsNumbers.length - 1);
for (var i = yaxis.ticksAsNumbers.length - 1; i > 0; i--) {
if (yaxis.ticksAsNumbers[i] < rules[ruleIndex].yAxisSegement) {
ctx.fillStyle = rules[ruleIndex].backgroundColor;
ctx.fillRect(xaxis.left, yaxis.top + ((i - 1) * (yaxis.height * partPercentage)), xaxis.width, yaxis.height * partPercentage);
} else {
ruleIndex++;
i++;
}
}
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>
Shiffty's answer is right on point, however it only works if the background values are present on the yAxis, which is not always the case... depends on what fits. A more generic solution is to calculate the actual values:
var canvas = document.getElementById('myChart');
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(51, 204, 51)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var myLineChart = new Chart(canvas,
{
type: 'line',
data: {
labels: ['1', '2', '3', '4', '5'],
datasets: [
{
label: '# of Votes',
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [2, 5, 12.5, 9, 6.3]
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Conditional Background'
},
backgroundRules: [{
backgroundColor: window.chartColors.green,
yAxisSegement: 6
}, {
backgroundColor: window.chartColors.grey,
yAxisSegement: 12
}, {
backgroundColor: window.chartColors.red,
yAxisSegement: 999999
}],
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
},
plugins: [{
beforeDraw: function (chart) {
var rules = chart.chart.options.backgroundRules;
var ctx = chart.chart.ctx;
var yAxis = chart.chart.scales["y-axis-0"];
var xaxis = chart.chart.scales["x-axis-0"];
for (var i = 0; i < rules.length; ++i) {
var yAxisSegement = (rules[i].yAxisSegement > yAxis.ticksAsNumbers[0] ? yAxis.ticksAsNumbers[0] : rules[i].yAxisSegement);
var yAxisPosStart = yAxis.height - ((yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]) + chart.chart.controller.chartArea.top;
var yAxisPosEnd = (i === 0 ? yAxis.height : yAxis.height - ((rules[i - 1].yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]));
ctx.fillStyle = rules[i].backgroundColor;
ctx.fillRect(xaxis.left, yAxisPosStart, xaxis.width, yAxisPosEnd - yAxisPosStart + chart.chart.controller.chartArea.top);
}
}
}]
});
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