I'm using Chart.js to draw a chart..
My dataset have some null values,
Actually chart.js plot a line between points that are previous and successor of the null values in this way :
The red arrow indicate where are the null values
I want to find how can I not plot these null values
The configuration I use is as simple as that :
var lineChartData = {
"datasets": [{
"label": "defi score",
"data": data,
"pointStrokeColor": "#fff",
"fillColor": "rgba(220,220,220,0.5)",
"pointColor": "rgba(220,220,220,1)",
"strokeColor": "rgba(220,220,220,1)",
}],
"labels": labels
};
var ctx = document.getElementById("chart_per_week").getContext("2d");
var myLine = new Chart(ctx).Line(lineChartData, {
responsive: true,
scaleFontColor: "#FF5972",
bezierCurve: false
});
Thank you for your help
In case you still reach this page, New version supports skipping missing data. .
If you want the lines to be connected by skipping missing data, you can set spanGaps: true in the options.
Then if you have null or NaN for missing data, it will skip it and connect to the next point.
.....
showTooltips: true,
options: {
spanGaps: true,
......
Documentation here
I know this is pretty old, but I think there is a better solution now. Replace all your null values with Number.NaN
http://www.chartjs.org/docs/#line-chart-chart-options
Below is a data point I replaced with NaN on the red line
Breaking (Broken) Lines using Chart.js
You can extend the line chart type to do this
Preview
Script
Chart.types.Line.extend({
name: "LineAlt",
initialize: function (data) {
var fillColors = [];
var strokeColors = [];
data.datasets.forEach(function (dataset, i) {
if (dataset.data.indexOf(null) !== -1) {
fillColors.push(dataset.fillColor);
strokeColors.push(dataset.strokeColor);
dataset.fillColor = "rgba(0,0,0,0)"
dataset.strokeColor = "rgba(0,0,0,0)"
}
})
Chart.types.Line.prototype.initialize.apply(this, arguments);
var self = this;
data.datasets.forEach(function (dataset, i) {
if (dataset.data.indexOf(null) !== -1) {
self.datasets[i]._saved = {
fillColor: fillColors.shift(),
strokeColor: strokeColors.shift()
}
}
})
},
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
// from Chart.js library code
var hasValue = function (point) {
return point.value !== null;
},
nextPoint = function (point, collection, index) {
return Chart.helpers.findNextWhere(collection, hasValue, index) || point;
},
previousPoint = function (point, collection, index) {
return Chart.helpers.findPreviousWhere(collection, hasValue, index) || point;
};
var ctx = this.chart.ctx;
var self = this;
ctx.save();
this.datasets.forEach(function (dataset) {
if (dataset._saved) {
ctx.lineWidth = self.options.datasetStrokeWidth;
ctx.strokeStyle = dataset._saved.strokeColor;
ctx.fillStyle = dataset._saved.fillColor;
// adapted from Chart.js library code
var pointsWithValues = Chart.helpers.where(dataset.points, hasValue);
dataset.points.forEach(function (point, index) {
if (index === 0 || (hasValue(point) && !hasValue(dataset.points[index - 1])))
point.start = true;
});
var currentStartPoint = undefined;
Chart.helpers.each(pointsWithValues, function (point, index) {
if (point.start) {
if (currentStartPoint) {
ctx.lineTo(pointsWithValues[index - 1].x, self.scale.endPoint);
ctx.lineTo(currentStartPoint.x, self.scale.endPoint);
ctx.closePath();
ctx.fill();
}
currentStartPoint = point;
ctx.beginPath();
ctx.moveTo(point.x, point.y);
}
else {
if (self.options.bezierCurve) {
var previous = previousPoint(point, pointsWithValues, index);
ctx.bezierCurveTo(
previous.controlPoints.outer.x,
previous.controlPoints.outer.y,
point.controlPoints.inner.x,
point.controlPoints.inner.y,
point.x,
point.y
);
}
else {
ctx.lineTo(point.x, point.y);
}
}
ctx.stroke();
}, this);
ctx.lineTo(pointsWithValues[pointsWithValues.length - 1].x, self.scale.endPoint);
ctx.lineTo(currentStartPoint.x, self.scale.endPoint);
ctx.closePath();
ctx.fill();
}
})
ctx.restore();
}
});
and then
var data = {
...
datasets: [
{
...
data: [65, 59, null, 81, 52, 62, null, 56, 40],
}
],
};
...
new Chart(ctx).LineAlt(data);
Fiddle - https://jsfiddle.net/hbrhz2q4/
I'm not sure if ChartJS itself can natively do this.
However one way I did something similar was to make the line graph out of multiple datasets. One dataset would end when a null value is reached, and the next dataset would start. This would of course requires parsing all this data before passing it into var linechartdata
You can make all the datasets have the same colors and highlights and the graph should render with spaces where null data would have been found.
Related
I have this code:
animation: {
duration: 500,
onComplete: function() {
var ctx = this.chart.ctx;
var chart = this;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
var datasets = this.config.data.datasets;
ctx.font = "15px QuickSand";
datasets.forEach(function (dataset, i) {
switch ( chart.getDatasetMeta(i).type ) {
case "bar":
ctx.fillStyle = "#303030";
chart.getDatasetMeta(i).data.forEach(function (p, j)
{
ctx.fillText(datasets[i].data[j], p._model.x, p._model.y - 10);
});
break;
}
});
}
}
And these datasets:
datasets: [
{
backgroundColor: '#f87979',
data: [6500, 5500]},
{
backgroundColor: '#f8f8ee',
data: [4800, 5600]
}
]
The dataset is set to be stacked using.
scales: {
xAxes: [{
barThickness: 25,
stacked: true,
ticks: {
beginAtZero: true,
padding: 0,
fontSize: 13
}
}],
yAxes: [{
stacked: true,
display: false
}]
},
What the above code does is placing the values over the bars. My problem is that i want to show the highest value from each dataset at above each bar.
And not all the values from each point.
Can you guys help me with this? I have been trying to do this for like a 1 day now.
To clearify instead of this:
Image with all values
I want this:
Image with wanted values
check out this jsfiddle: https://jsfiddle.net/umsbywLg/2/
essentially I calculated the max value and then drew that on top on the stacked bars:
onComplete: function() {
var ctx = this.chart.ctx;
var chart = this;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
var datasets = this.config.data.datasets;
ctx.font = "15px QuickSand";
ctx.fillStyle = "#303030";
datasets.forEach(function (dataset, i) {
var maxValue = 0;
chart.getDatasetMeta(i).data.forEach(function (p, j) {
if(maxValue < datasets[j].data[i]) {
maxValue = datasets[j].data[i];
}
});
ctx.fillText(maxValue, datasets[i]._meta[0].data[i]._view.x, 20);
});
}
I need to render some line that has many points (200) and at the beginning x equals y.
But as you can see on this codepen, the line is not straight.
Is there a way to have a smooth rendering ?
Thank you very much
var ctx = document.getElementById("myChart");
function generateFakeData() {
var res = [];
var i = 0;
for (i = 0; i < 200; ++i) {
res.push(i);
}
return res;
}
var myChart = new Chart(ctx, {
type: "line",
data: {
labels: generateFakeData(),
datasets: [
{
label: "# of Votes",
data: generateFakeData(),
radius: 0,
borderColor: "#156FB4"
}
]
},
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
}
});
If you were to change your fake data function to be:
function generateFakeData() {
var res = [];
res[0] = 0;
res[200] = 200;
return res;
}
and add spanGaps: true to the options, the line will be nice and straight, otherwise the way the pixels line up will make it look jagged as it tries to connect each one.
Not sure if this helps with your use case.
I am looking for a way to fill between two lines with Chart.js so that it would look like this. I have looked and everything seems to talk about filling between two lines across zero. I also need other lines to fill all the way down like normal. Is this something chart.js can do?
Here is a solution that uses a plugin to fill between two datasets. Supports all line styles and fill shading between multiple lines. To fill between a dataset, use the custom param fillBetweenSet to tell a dataset to fill the area between another dataset.
Fiddle - https://jsfiddle.net/ke5n5LnL/26/
Preview:
Code:
<html>
<div>
<canvas id="demo"></canvas>
</div>
</html>
<script>
var fillBetweenLinesPlugin = {
afterDatasetsDraw: function (chart) {
var ctx = chart.chart.ctx;
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-0'];
var datasets = chart.data.datasets;
ctx.save();
for (var d = 0; d < datasets.length; d++) {
var dataset = datasets[d];
if (dataset.fillBetweenSet == undefined) {
continue;
}
// get meta for both data sets
var meta1 = chart.getDatasetMeta(d);
var meta2 = chart.getDatasetMeta(dataset.fillBetweenSet);
// do not draw fill if one of the datasets is hidden
if (meta1.hidden || meta2.hidden) continue;
// create fill areas in pairs
for (var p = 0; p < meta1.data.length-1;p++) {
// if null skip
if (dataset.data[p] == null || dataset.data[p+1] == null) continue;
ctx.beginPath();
// trace line 1
var curr = meta1.data[p];
var next = meta1.data[p+1];
ctx.moveTo(curr._view.x, curr._view.y);
ctx.lineTo(curr._view.x, curr._view.y);
if (curr._view.steppedLine === true) {
ctx.lineTo(next._view.x, curr._view.y);
ctx.lineTo(next._view.x, next._view.y);
}
else if (next._view.tension === 0) {
ctx.lineTo(next._view.x, next._view.y);
}
else {
ctx.bezierCurveTo(
curr._view.controlPointNextX,
curr._view.controlPointNextY,
next._view.controlPointPreviousX,
next._view.controlPointPreviousY,
next._view.x,
next._view.y
);
}
// connect dataset1 to dataset2
var curr = meta2.data[p+1];
var next = meta2.data[p];
ctx.lineTo(curr._view.x, curr._view.y);
// trace BACKWORDS set2 to complete the box
if (curr._view.steppedLine === true) {
ctx.lineTo(curr._view.x, next._view.y);
ctx.lineTo(next._view.x, next._view.y);
}
else if (next._view.tension === 0) {
ctx.lineTo(next._view.x, next._view.y);
}
else {
// reverse bezier
ctx.bezierCurveTo(
curr._view.controlPointPreviousX,
curr._view.controlPointPreviousY,
next._view.controlPointNextX,
next._view.controlPointNextY,
next._view.x,
next._view.y
);
}
// close the loop and fill with shading
ctx.closePath();
ctx.fillStyle = dataset.fillBetweenColor || "rgba(0,0,0,0.1)";
ctx.fill();
} // end for p loop
}
} // end afterDatasetsDraw
}; // end fillBetweenLinesPlugin
Chart.pluginService.register(fillBetweenLinesPlugin);
var chartData = {
labels: [1, 2, 3, 4, 5,6,7,8],
datasets: [
{
label: "Set 1",
data: [10, 20, null, 40, 30,null,20,40],
borderColor: "#F00",
fill: false,
steppedLine: false,
tension: 0,
fillBetweenSet: 1,
fillBetweenColor: "rgba(255,0,0, 0.2)"
},
{
label: "Set 2",
data: [60, 40, 10, 50, 60,null,50,20],
borderColor: "#00F",
fill: false,
steppedLine: false,
tension: 0.5
},
{
label: "Set 2",
data: [40, 50, 30, 30, 20,null,60,40],
borderColor: "#0D0",
fill: false,
steppedLine: false,
tension: 0,
fillBetweenSet: 1,
fillBetweenColor: "rgba(5,5,255, 0.2)"
}
]
};
var chartOptions = {
responsive: true,
title: {
display: true,
text: 'Demo Fill between lines'
}
};
var chartDemo = new Chart($('#demo').get(0), {
type: 'line',
data: chartData,
options: chartOptions
});
</script>
Setting fill property to +1 of a dataset will set the backgroundColor from this line to the next line in dataset.
datasets: [{
label: 'Systolic Guideline',
data: [],
fill: '+1',
borderColor: '#FFC108',
backgroundColor: 'rgba(255,193,8,0.2)'
},
{
label: 'Diastolic Guideline',
data: [],
fill: true,
borderColor: '#FFC108',
backgroundColor: 'rgba(0,0,0,0)'
}]
On chart.js v2.0 you have this feature now inside. See https://www.chartjs.org/samples/latest/charts/area/line-datasets.html
In the javascript graphing library, is there a way I can change the line segment color of the line between two adjacent points?
Thanks
You can extend the chart to redraw the segment of your choice with the different color.
Preview
Script
Chart.types.Line.extend({
name: "LineAlt",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var index = 1;
var datasetIndex = 0;
var hasValue = function(item){
return item.value !== null;
},
previousPoint = function (point, collection, index) {
return Chart.helpers.findPreviousWhere(collection, hasValue, index) || point;
};
var ctx = this.chart.ctx;
var dataset = this.datasets[datasetIndex];
var pointsWithValues = Chart.helpers.where(dataset.points, hasValue);
ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.beginPath();
var point = dataset.points[index];
ctx.moveTo(point.x, point.y);
point = dataset.points[index + 1];
var previous = previousPoint(point, pointsWithValues, index + 1);
ctx.bezierCurveTo(
previous.controlPoints.outer.x,
previous.controlPoints.outer.y,
point.controlPoints.inner.x,
point.controlPoints.inner.y,
point.x,
point.y
);
ctx.stroke();
}
});
and
...
new Chart(ctx).LineAlt(data);
Fiddle - http://jsfiddle.net/021xvuhd/10/
Here's a working example to do this in Charts.js 2
https://jsfiddle.net/egamegadrive16/zjdwr4fh/
var ctx = document.getElementById('myChart').getContext('2d');
//adding custom chart type
Chart.defaults.multicolorLine = Chart.defaults.line;
Chart.controllers.multicolorLine = Chart.controllers.line.extend({
draw: function(ease) {
var
startIndex = 0,
meta = this.getMeta(),
points = meta.data || [],
colors = this.getDataset().colors,
area = this.chart.chartArea,
originalDatasets = meta.dataset._children
.filter(function(data) {
return !isNaN(data._view.y);
});
function _setColor(newColor, meta) {
meta.dataset._view.borderColor = newColor;
}
if (!colors) {
Chart.controllers.line.prototype.draw.call(this, ease);
return;
}
for (var i = 2; i <= colors.length; i++) {
if (colors[i-1] !== colors[i]) {
_setColor(colors[i-1], meta);
meta.dataset._children = originalDatasets.slice(startIndex, i);
meta.dataset.draw();
startIndex = i - 1;
}
}
meta.dataset._children = originalDatasets.slice(startIndex);
meta.dataset.draw();
meta.dataset._children = originalDatasets;
points.forEach(function(point) {
point.draw(area);
});
}
});
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'multicolorLine',
// The data for our dataset
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
//first color is not important
colors: ['', 'red', 'green', 'blue']
}]
},
// Configuration options go here
options: {}
});
source: https://github.com/chartjs/Chart.js/issues/4895#issuecomment-342747042
It's now built into CHart.js 3:
https://www.chartjs.org/docs/latest/samples/line/segments.html
We have been using Chart.js for several months now and like the power it gives us with ease of programming. One of the things we would like to start adding to the charts produced from Chart.js is a little nicer styling of the charts we generate. Most of the charts we are using are bar charts, with a few line charts thrown in.
When I use the term "styling" what I am really talking about is making the bars or lines look a little nicer. Specifically I would like to add a drop shadow behind the bar and line charts, and maybe even a bevel to the bars.
I've looked through many questions, and can't seem to find what I am looking for. I've also done some experimenting myself by modifying the Chart.js file to add a drop shadow and blur to the javascript, but I'm not getting it added in the correct place. I put these changes inside of the Chart.Element.extend draw function:
ctx.shadowColor = '#000';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 8;
ctx.shadowOffsetY = 8;
I put it right before the ctx.fill() and it almost does what I want. The result is I get a drop shadow that looks pretty good on both the bar and line charts I am drawing, but I also get a drop shadow on the labels for the x and y axes, which does not look good. I'd like to have the drop shadow on just the bars and the lines, not on the labels.
Any help you can provide would be greatly appreciated. I am not experienced with javascript, but have been able to pull off quite a bit of coding I wouldn't otherwise be able to do without the help of everyone on Stack Overflow.
Adding a Drop Shadow for Line Charts
You can extend the line chart type to do this
Preview
Script
Chart.types.Line.extend({
name: "LineAlt",
initialize: function () {
Chart.types.Line.prototype.initialize.apply(this, arguments);
var ctx = this.chart.ctx;
var originalStroke = ctx.stroke;
ctx.stroke = function () {
ctx.save();
ctx.shadowColor = '#000';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 8;
ctx.shadowOffsetY = 8;
originalStroke.apply(this, arguments)
ctx.restore();
}
}
});
and then
...
var myChart = new Chart(ctx).LineAlt(data, {
datasetFill: false
});
Fiddle - https://jsfiddle.net/7kbz1L4t/
ππππππππ πππ π²πππππΉπ πΈ.π‘.π‘
α΄Κα΄α΄ Ιͺα΄α΄‘
κ±α΄ΚΙͺα΄α΄βoverriding the draw function
let draw = Chart.controllers.line.prototype.draw;
Chart.controllers.line.prototype.draw = function() {
draw.apply(this, arguments);
let ctx = this.chart.chart.ctx;
let _stroke = ctx.stroke;
ctx.stroke = function() {
ctx.save();
ctx.shadowColor = '#07C';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 4;
_stroke.apply(this, arguments);
ctx.restore();
}
};
let draw = Chart.controllers.line.prototype.draw;
Chart.controllers.line.prototype.draw = function() {
draw.apply(this, arguments);
let ctx = this.chart.chart.ctx;
let _stroke = ctx.stroke;
ctx.stroke = function() {
ctx.save();
ctx.shadowColor = '#07C';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 4;
_stroke.apply(this, arguments);
ctx.restore();
}
};
let ctx = document.querySelector("#canvas").getContext('2d');
let myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
data: [65, 59, 75, 64, 70, 30, 40],
borderColor: '#07C',
pointBackgroundColor: "#FFF",
pointBorderColor: "#07C",
pointHoverBackgroundColor: "#07C",
pointHoverBorderColor: "#FFF",
pointRadius: 4,
pointHoverRadius: 4,
fill: false,
tension: 0.15
}]
},
options: {
responsive: false,
tooltips: {
displayColors: false,
callbacks: {
label: function(e, d) {
return `${e.xLabel} : ${e.yLabel}`
},
title: function() {
return;
}
}
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
max: 90
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="canvas" width="400" height="210" style="background-color: #E4E8F0"></canvas>
This works for new version of Chart JS
We can create a plugin object and register to the chart JS, Plugins are a way for a developer to modify a chart as it is being created, for reference please look at
https://riptutorial.com/chart-js/example/22332/plugins-introduction
Example Plugin to add a shadow to any of the chart
var simpleplugin = {
beforeDraw : function(chartInstance)
{
let _stroke = chartInstance.ctx.stroke;
chartInstance.ctx.stroke = function () {
chartInstance.ctx.save();
chartInstance.ctx.shadowColor = 'gray';
chartInstance.ctx.shadowBlur = 10;
chartInstance.ctx.shadowOffsetX = 2;
chartInstance.ctx.shadowOffsetY = 2;
_stroke.apply(this, arguments)
chartInstance.ctx.restore();
}
let _fill = chartInstance.ctx.fill;
ctx.fill = function () {
chartInstance.ctx.save();
chartInstance.ctx.shadowColor = 'gray';
chartInstance.ctx.shadowBlur = 10;
chartInstance.ctx.shadowOffsetX = 2;
chartInstance.ctx.shadowOffsetY = 2;
_fill.apply(this, arguments)
chartInstance.ctx.restore();
}
}
}
$(function()
{
Chart.pluginService.register(simpleplugin);
});