How to add an end line to my graph using Chart.js? - javascript

I have drawn a Chart using Chart.js. It does not automatically draw an end line at the end(right side) of the Chart:
I have used plugin code to hide the overlaying vertical lines which are drawn by Chartjs automatically. I could not find another way to hide those. Here is the code which describes the Chart.
function getHydrationOverviewChart(elementID) {
Chart.plugins.register({
beforeDraw: function(chart) {
var ctx = chart.chart.ctx,
x_axis = chart.scales['x-axis-0'],
topY = chart.scales['y-axis-0'].top,
bottomY = chart.scales['y-axis-0'].bottom;
x_axis.options.gridLines.display = false;
x_axis.ticks.forEach(function(label, index) {
var x = x_axis.getPixelForValue(label);
ctx.save();
ctx.beginPath();
ctx.lineWidth = 1;
ctx.strokeStyle = x_axis.options.gridLines.color;
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.stroke();
ctx.restore();
});
}
});
var options = {
type: 'bar',
data: {
labels: ["1", "2", "3", "4", "5"],
datasets: [
{
borderWidth: 2,
borderColor: "#5d5d5d",
pointBorderColor: "#5d5d5d",
pointBackgroundColor: "#5d5d5d",
pointBorderWidth: 5,
type: 'line',
data: [26, 26, 33, 28, 30],
fill: false,
lineTension: 0
},
{
borderWidth: 3,
pointBorderColor: "#b8b8b8",
pointBackgroundColor: "#b8b8b8",
pointBorderWidth: 10,
type: 'line',
data: [26, 26, 29, 28, 29],
fill: false,
lineTension: 0
},
{
data: [0, 0, 0, 0, 0],
fill: false,
lineTension: 0
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
hover: {mode: null},
legend: {
display: false
},
tooltips: {enabled: false},
hover: {mode: null},
scales: {
xAxes: [{
gridLines: {
// drawBorder: false,
},
}],
yAxes: [{
display: false,
ticks: {
suggestedMin: 0,
max: 60,
beginAtZero: true
}
}]
}
}
}
var ctx = document.getElementById(elementID).getContext('2d');
new Chart(ctx, options);
}
Does anybody know how I can add this vertical endline?

This can be accomplished using the following chart plugin :
Chart.plugins.register({
beforeDraw: function(chart) {
var ctx = chart.chart.ctx,
x_axis = chart.scales['x-axis-0'],
topY = chart.scales['y-axis-0'].top,
bottomY = chart.scales['y-axis-0'].bottom;
x_axis.options.gridLines.display = false;
for (i = 0; i <= x_axis.ticks.length; i++) {
var x = i === x_axis.ticks.length ?
x_axis.right :
x_axis.getPixelForValue(x_axis.ticks[i]);
ctx.save();
ctx.beginPath();
ctx.lineWidth = 1;
ctx.strokeStyle = x_axis.options.gridLines.color;
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.stroke();
ctx.restore();
}
}
});
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
Chart.plugins.register({
beforeDraw: function(chart) {
var ctx = chart.chart.ctx,
x_axis = chart.scales['x-axis-0'],
topY = chart.scales['y-axis-0'].top,
bottomY = chart.scales['y-axis-0'].bottom;
x_axis.options.gridLines.display = false;
for (i = 0; i <= x_axis.ticks.length; i++) {
var x = i === x_axis.ticks.length ?
x_axis.right :
x_axis.getPixelForValue(x_axis.ticks[i]);
ctx.save();
ctx.beginPath();
ctx.lineWidth = 1;
ctx.strokeStyle = x_axis.options.gridLines.color;
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.stroke();
ctx.restore();
}
}
});
var options = {
type: 'bar',
data: {
labels: ["1", "2", "3", "4", "5"],
datasets: [{
borderWidth: 2,
borderColor: "#5d5d5d",
pointBorderColor: "#5d5d5d",
pointBackgroundColor: "#5d5d5d",
pointBorderWidth: 5,
type: 'line',
data: [26, 26, 33, 28, 30],
fill: false,
lineTension: 0
}, {
borderWidth: 3,
pointBorderColor: "#b8b8b8",
pointBackgroundColor: "#b8b8b8",
pointBorderWidth: 10,
type: 'line',
data: [26, 26, 29, 28, 29],
fill: false,
lineTension: 0
}, {
data: [0, 0, 0, 0, 0],
fill: false,
lineTension: 0
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
hover: {
mode: null
},
legend: {
display: false
},
tooltips: {
enabled: false
},
hover: {
mode: null
},
scales: {
xAxes: [{
gridLines: {
// drawBorder: false,
},
}],
yAxes: [{
display: false,
ticks: {
suggestedMin: 0,
max: 60,
beginAtZero: true
}
}]
}
}
}
var ctx = document.getElementById('canvas').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas" height="400"></canvas>

Related

Is it possible to make points in a line chart of Chart JS 3.7.0 look like a donut?

the version of Chart JS is 3.7.0
I am looking for a way to make my chart's points look from this:
to something like this:
I found out that there is an option in this library where you can set the points to a certain shape. e.x: pointStyle: 'rectRot' will make the points appearance look like this:
Is there an option or a way to achieve what Im looking for? (Check the second picture).
Thanks in advance!
My chart's javascript:
const data = {
datasets: [
{
backgroundColor: 'black',
borderColor: '#2d84b4',
borderWidth: 2,
data: [
{ x: 'Dec 27', y: 0.204 },
{ x: '01:00', y: 0.234 },
{ x: '02:00', y: 0.274 },
{ x: '03:00', y: 0.234 },
{ x: '04:00', y: 0.304 },
{ x: 'Dec 28', y: 0.506 },
],
fill: false,
pointBorderColor: 'rgba(0, 0, 0, 0)',
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: '#2d84b4',
pointHoverBorderColor: '#2d84b4',
},
],
};
const config = {
type: 'line',
data: data,
options: {
animation: {
duration: 0,
},
responsive: true,
maintainAspectRatio: false,
plugins: {
//Do not display legend.
legend: {
display: false,
},
},
scales: {
xAxes: {
stacked: true,
ticks: {
stepSize: 2,
},
grid: {
display: true,
drawBorder: false,
drawOnChartArea: false,
drawTicks: true,
tickLength: 4,
type: 'time',
},
},
yAxes: {
grid: {
drawBorder: false,
drawTicks: false,
},
},
},
elements: {
point: {
radius: 5,
},
},
},
};
// Initialize the Chart.
const myChart = new Chart(document.getElementById('myChart'), config);
window.addEventListener('beforeprint', () => {
myChart.resize(600, 600);
});
window.addEventListener('afterprint', () => {
myChart.resize();
});
//Disable all animations!
myChart.options.animation = false;
myChart.options.animations.colors = false;
myChart.options.animations.x = false;
myChart.options.transitions.active.animation.duration = 0;
The points seemed to work just fine with your transparent background, only on hover you setted a normal background again so the pointHoverBackgroundColor should also be transparent.
To make the point bigger on hover you can use the hoverRadius and to make the line have the same width you can use the pointHoverBorderWidth:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'black',
borderColor: '#2d84b4',
borderWidth: 2,
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBorderColor: '#2d84b4',
hoverRadius: 10,
pointHoverBorderWidth: 2
}]
},
options: {}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

Chart.js Fill color at null line and null points Tooltip

I have the following code. The line is blue and if data is null, a red line is drawn. This already works quite well.
But how do I add a corresponding fill color (blue for blue and red for red)?
And how do I make it so that the tooltip points are set despite null?
I have already tried to add fill: true, and backgroundColor: '#blue', in the datasets but it did not bring the desired result.
var ctx = document.getElementById("canvas").getContext("2d");
var myChart = new Chart(ctx, {
type: 'line',
plugins: [{
beforeDraw: chart => {
var ctx = chart.chart.ctx;
ctx.save();
let xAxis = chart.scales['x-axis-0'];
let yAxis = chart.scales['y-axis-0'];
let dataset = chart.data.datasets[0];
var valueFrom = null;
var valueFromIndex = 0;
var xFrom = null;
let yFrom = null;
ctx.strokeStyle = dataset.borderColor;
ctx.fillStyle = dataset.backgroundColor;
ctx.label = dataset.label;
dataset.data.forEach((value, index) => {
if (value != null) {
var x = xAxis.getPixelForTick(index);
var y = yAxis.getPixelForValue(value);
if (valueFrom != null) {
ctx.lineWidth = dataset.borderWidth;
if (index - valueFromIndex > 1) {
ctx.setLineDash([]);
ctx.strokeStyle = '#ff0000';
} else {
ctx.setLineDash([]);
ctx.strokeStyle = '#3d93a8';
}
ctx.beginPath();
ctx.moveTo(xFrom, yFrom);
ctx.lineTo(x, y);
ctx.stroke();
}
valueFrom = value;
valueFromIndex = index;
xFrom = x;
yFrom = y;
}
});
ctx.restore();
}
}],
data: {
labels: ["1","2","3","4","5","6","7","8"],
datasets: [{
label: "Number",
data: [20,15,null,18,21,null,8,16],
pointBackgroundColor: '#000000',
pointRadius: 0.0,
pointHoverRadius: 0.0,
pointStyle: 'rectRounded',
borderColor: '#3d93a8',
lineTension: 0.6,
borderWidth: 2.5,
showLine: false,
}]
},
options: {
title: {
display: true,
fontStyle: 'bold',
fontSize: '20',
fontColor: '#000',
position: 'top',
lineHeight: 1.0,
text: 'Description',
},
legend: {
display: false,
position: "butt",
labels: {}
},
tooltips: {
enabled: true,
mode: 'index',
intersect: false,
xPadding: 15,
bodySpacing: 0,
cornerRadius: 10,
titleMarginBottom: 5,
position: 'nearest',
titleAlign: 'center',
},
animation: {
duration: 0
},
scales: {
xAxes: [{
stacked: true,
barThickness: 'flex',
maxBarThickness: 100,
gridLines: {
display:false
},
ticks: {
autoSkip: true,
maxTicksLimit: 24
},
}],
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
},
chartArea: {
backgroundColor: '#e8e8e8'
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="canvas" width="auto" height="100%"></canvas>
Instead of drawing the lines within the beforeDraw hook, you can compute and define the borderColor and backgroundColor of the dataset inside the afterLayout hook using CanvasRenderingContext2D.createLinearGradient(). This has the advantage that the lineTension option will also be considered and you'll obtain a nice looking Bezier curve.
To make it work, you'll also have to define spanGaps: true on the dataset. This instructs Chart.js to draw lines between points, even if there are null values in between.
afterLayout: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let xAxis = chart.scales['x-axis-0'];
let borderGradient = ctx.createLinearGradient(xAxis.left, 0, xAxis.right, 0);
let bgGradient = ctx.createLinearGradient(xAxis.left, 0, xAxis.right, 0);
let dataset = chart.data.datasets[0];
dataset.data.forEach((value, index) => {
if (index > 0) {
let valueFrom = dataset.data[index - 1];
let valueTo = dataset.data[index + 1];
let xFrom = xAxis.getPixelForValue(valueFrom);
let xTo = xAxis.getPixelForTick(index);
let offset = 1 / (xAxis.right - xAxis.left) * (xTo - xAxis.left);
borderGradient.addColorStop(offset, valueFrom == null || value == null ? '#ff0000' : '#3d93a8');
borderGradient.addColorStop(offset, value == null || valueTo == null ? '#ff0000' : '#3d93a8');
bgGradient.addColorStop(offset, valueFrom == null || value == null ? 'rgba(255, 0, 0, 0.5)' : 'rgba(61, 147, 168, 0.5)');
bgGradient.addColorStop(offset, value == null || valueTo == null ? 'rgba(255, 0, 0, 0.5)' : 'rgba(61, 147, 168, 0.5)');
}
});
dataset.borderColor = borderGradient;
dataset.backgroundColor = bgGradient;
ctx.restore();
}
Please take a look at your amended and runnable code below:
new Chart('canvas', {
type: 'line',
plugins: [{
afterLayout: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let xAxis = chart.scales['x-axis-0'];
let borderGradient = ctx.createLinearGradient(xAxis.left, 0, xAxis.right, 0);
let bgGradient = ctx.createLinearGradient(xAxis.left, 0, xAxis.right, 0);
let dataset = chart.data.datasets[0];
dataset.data.forEach((value, index) => {
if (index > 0) {
let valueFrom = dataset.data[index - 1];
let valueTo = dataset.data[index + 1];
let xFrom = xAxis.getPixelForValue(valueFrom);
let xTo = xAxis.getPixelForTick(index);
let offset = 1 / (xAxis.right - xAxis.left) * (xTo - xAxis.left);
borderGradient.addColorStop(offset, valueFrom == null || value == null ? '#ff0000' : '#3d93a8');
borderGradient.addColorStop(offset, value == null || valueTo == null ? '#ff0000' : '#3d93a8');
bgGradient.addColorStop(offset, valueFrom == null || value == null ? 'rgba(255, 0, 0, 0.5)' : 'rgba(61, 147, 168, 0.5)');
bgGradient.addColorStop(offset, value == null || valueTo == null ? 'rgba(255, 0, 0, 0.5)' : 'rgba(61, 147, 168, 0.5)');
}
});
dataset.borderColor = borderGradient;
dataset.backgroundColor = bgGradient;
ctx.restore();
}
}],
data: {
labels: ["1", "2", "3", "4", "5", "6", "7", "8"],
datasets: [{
label: "Number",
data: [20, 15, null, 18, 21, null, 8, 16],
pointRadius: 0.0,
pointHoverRadius: 0.0,
lineTension: 0.6,
borderWidth: 2.5,
spanGaps: true
}]
},
options: {
title: {
display: true,
fontStyle: 'bold',
fontSize: '20',
fontColor: '#000',
position: 'top',
lineHeight: 1.0,
text: 'Description',
},
legend: {
display: false,
position: "butt",
labels: {}
},
tooltips: {
enabled: true,
mode: 'index',
intersect: false,
xPadding: 15,
bodySpacing: 0,
cornerRadius: 10,
titleMarginBottom: 5,
position: 'nearest',
titleAlign: 'center',
},
animation: {
duration: 0
},
scales: {
xAxes: [{
stacked: true,
barThickness: 'flex',
maxBarThickness: 100,
gridLines: {
display: false
},
ticks: {
autoSkip: true,
maxTicksLimit: 24
},
}],
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="canvas" width="auto" height="100%"></canvas>

Grouped bar chart with label in Chart.js

I need to recreate a chart very similar to this one:
While researching I found this example:
https://codepen.io/bencarmichael/pen/XeYJXJ
datasets: [
{
label: "American Express",
backgroundColor: "pink",
borderColor: "red",
borderWidth: 1,
data: [3, 5, 6, 7,3, 5, 6, 7] // I need labels on this values
}
]
It shows grouped bar charts. But it's lacking a label per bar. If it's not possible on Chart.js, it can be any other library.
use this code
View result in full screen mode
this is copied from the example you provided in you Question
var barChartData = {
labels: [
"Absence of OB",
"Closeness",
"Credibility",
"Heritage",
"M Disclosure",
"Provenance",
"Reliability",
"Transparency"
],
datasets: [
{
label: "American Express",
backgroundColor: "pink",
borderColor: "red",
borderWidth: 1,
data: [3, 5, 6, 7,3, 5, 6, 7],
},
{
label: "Mastercard",
backgroundColor: "lightblue",
borderColor: "blue",
borderWidth: 1,
data: [4, 7, 3, 6, 10,7,4,6]
},
{
label: "Paypal",
backgroundColor: "lightgreen",
borderColor: "green",
borderWidth: 1,
data: [10,7,4,6,9,7,3,10]
},
{
label: "Visa",
backgroundColor: "yellow",
borderColor: "orange",
borderWidth: 1,
data: [6,9,7,3,10,7,4,6]
}
]
};
var chartOptions = {
responsive: true,
legend: {
position: "top"
},
"hover": {
"animationDuration": 0
},
legend: {
"display": false
},
tooltips: {
"enabled": true
},
"animation": {
"duration": 1,
"onComplete": function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i) {
debugger
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.font = '10pt Verdana';
ctx.save();
ctx.translate(0,500);
ctx.rotate(-0.5*Math.PI);
var rText = 'My test value ='+data ;
ctx.fillText(rText , 90, bar._model.x+5);
ctx.restore();
});
});
}
},
title: {
display: true,
text: "Chart.js Bar Chart"
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: "bar",
data: barChartData,
options: chartOptions
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div>

Can't display proper time on chart.js timeline

I'm trying to create chart using Chart.js library. The X axis must be a timeline with this kind of time format: DD-MM-YYYY HH:MM:SS, but on the chart it gives incorrect dates and even my data does not display properly. If I remove HH:MM:SS part, the rest works fine. What's the problem? How can I display time in DD-MM-YYYY HH:MM:SS fromat?
Here is my fiddle: http://jsfiddle.net/vaxobasilidze/ak1vmj9q/
function factorData(data) {
let _data = data.map((e, i, a) => {
let prev = a[i - 1];
let next = a[i + 1];
if (e === prev && e === next) return '' + e;
return e;
}).map(e => typeof e === 'string' ? null : e);
return _data;
}
var ctx = document.getElementById('chart').getContext('2d');
var gradient1 = ctx.createLinearGradient(0, 0, 0, 400);
gradient1.addColorStop(0, 'rgba(14, 22, 38, 1)');
gradient1.addColorStop(1, 'rgba(1, 103, 147, 0.7)');
/***************/
var datas = [];
datas.push({x: "01-04-2001 10:05:46", y: 175});
datas.push({x: "01-10-2002 10:15:46", y: 140});
datas.push({x: "01-07-2003 11:47:26", y: 98});
datas.push({x: "01-10-2003 01:07:42", y: 130});
datas.push({x: "01-09-2006 06:55:46", y: 164});
datas.push({x: "01-04-2013 10:22:35", y: 178});
datas.push({x: "01-10-2015 10:05:46", y: 118});
datas.push({x: "01-10-2018 10:05:46", y: 158});
var timeFormat = "DD-MM-YYYY HH:MM:SS";
var options = {
type: 'line',
data: {
datasets: [{
fillColor: gradient1,
backgroundColor: gradient1,
borderColor: gradient1,
fill: 'origin',
strokeColor: gradient1,
pointBackgroundColor: "#00b2ff",
pointRadius: 2,
pointBorderWidth: 0,
pointHoverRadius: 3,
pointHoverBackgroundColor: "rgba(0, 178, 255, 1)",
data: datas,
steppedLine: true,
spanGaps: true
}, ]
},
options: {
responsive: true,
maintainAspectRatio: false,
datasetStrokeWidth: 1,
pointDotRadius: 3,
pointDotStrokeWidth: 1,
pointHitDetectionRadius: 1,
tooltipFillColor: "rgba(120,0,0,0.8)",
tooltipFontStyle: "bold",
animation: false,
scaleFontColor: "#ffffff",
scaleFontStyle: "bold",
scales: {
xAxes: [{
type: "time",
time: {
format: timeFormat,
tooltipFormat: 'll',
min: new Date(2001, 1, 4, 1, 0, 0, 0),
},
ticks: {
maxTicksLimit: 21,
minRotation: 90,
fontColor: '#ffffff'
},
gridLines: {
color: "#444444"
}
}],
yAxes: [{
ticks: {
fontColor: '#ffffff'
},
gridLines: {
color: "#444444"
},
}]
}
},
}
var myLineChart = new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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.3/Chart.min.js"></script>
<canvas id="chart" width="800" height="400" style="background: #202020"></canvas>
I believe you're looking for DD-MM-YYYY HH:mm:ss See moment.js for a list of allowable format tokens (chart.js uses the same formats which is specified here).
MM is for months (as you're using currectly in the DD-MM-YYYY section and SS is for fractional seconds. I dont think you are wanting either of those to display the time (could be wrong about that on the fractional seconds but definitely not months being the minutes)
If you're wanting your labels to have the time on them as well then you can use:
`type: "time",
time: {
displayFormats:{ timeFormat },
min: new Date(2001, 1, 4, 1, 0, 0, 0),
},`
Both of these solutions combined yield the following chart:
function factorData(data) {
let _data = data.map((e, i, a) => {
let prev = a[i - 1];
let next = a[i + 1];
if (e === prev && e === next) return '' + e;
return e;
}).map(e => typeof e === 'string' ? null : e);
return _data;
}
var ctx = document.getElementById('chart').getContext('2d');
var gradient1 = ctx.createLinearGradient(0, 0, 0, 400);
gradient1.addColorStop(0, 'rgba(14, 22, 38, 1)');
gradient1.addColorStop(1, 'rgba(1, 103, 147, 0.7)');
/***************/
/* var datas = [];
var labelss = [];
var quantity = 50;
for (var i = 0; i < quantity; i++) {
var test = Math.floor((Math.random() * 100) + 1);
datas.push(test);
labelss.push(i);
} */
var datas = [];
datas.push({x: "01-04-2001 10:05:46", y: 175});
datas.push({x: "01-10-2002 10:15:46", y: 140});
datas.push({x: "01-07-2003 11:47:26", y: 98});
datas.push({x: "01-10-2003 01:07:42", y: 130});
datas.push({x: "01-09-2006 06:55:46", y: 164});
datas.push({x: "01-04-2013 10:22:35", y: 178});
datas.push({x: "01-10-2015 10:05:46", y: 118});
datas.push({x: "01-10-2018 10:05:46", y: 158});
var timeFormat = "DD-MM-YYYY HH:mm:ss";
var options = {
type: 'line',
data: {
//labels: labelss,
datasets: [{
fillColor: gradient1,
backgroundColor: gradient1,
borderColor: gradient1,
fill: 'origin',
strokeColor: gradient1,
pointBackgroundColor: "#00b2ff",
pointRadius: 2,
pointBorderWidth: 0,
pointHoverRadius: 3,
pointHoverBackgroundColor: "rgba(0, 178, 255, 1)",
data: datas,
steppedLine: true,
spanGaps: true
}, ]
},
options: {
responsive: true,
maintainAspectRatio: false,
datasetStrokeWidth: 1,
pointDotRadius: 3,
pointDotStrokeWidth: 1,
pointHitDetectionRadius: 1,
tooltipFillColor: "rgba(120,0,0,0.8)",
tooltipFontStyle: "bold",
animation: false,
scaleFontColor: "#ffffff",
scaleFontStyle: "bold",
scales: {
xAxes: [{
type: "time",
time: {
displayFormats:{ timeFormat },
min: new Date(2001, 1, 4, 1, 0, 0, 0)
},
ticks: {
maxTicksLimit: 21,
minRotation: 90,
fontColor: '#ffffff'
},
gridLines: {
color: "#444444"
}
}],
yAxes: [{
ticks: {
fontColor: '#ffffff'
},
gridLines: {
color: "#444444"
},
}]
}
},
}
var myLineChart = new Chart(ctx, options);

How to remove the unnecessary overlaying gridlines using Chart.js?

I have drawn a chart using Chartjs. I can explain the pixels I want to remove, but I think an image makes it a lot clearer:
Underneath is the code which generates this graph:
var options = {
type: 'bar',
data: {
labels: ["1", "2", "3", "4", "5"],
datasets: [
{
borderWidth: 2,
borderColor: "#5d5d5d",
pointBorderColor: "#5d5d5d",
pointBackgroundColor: "#5d5d5d",
pointBorderWidth: 5,
type: 'line',
data: [26, 26, 33, 28, 30],
fill: false,
lineTension: 0
},
{
borderWidth: 3,
pointBorderColor: "#b8b8b8",
pointBackgroundColor: "#b8b8b8",
pointBorderWidth: 10,
type: 'line',
data: [26, 26, 29, 28, 29],
fill: false,
lineTension: 0
},
{
data: [0, 0, 0, 0, 0],
fill: false,
lineTension: 0
}
]
},
options: {
hover: {mode: null},
legend: {
display: false
},
tooltips: {enabled: false},
hover: {mode: null},
scales: {
xAxes: [{
gridLines: {
// drawBorder: false,
},
}],
yAxes: [{
display: false,
ticks: {
suggestedMin: 0,
max: 60,
beginAtZero: true
}
}]
}
}
}
var ctx = document.getElementById(elementID).getContext('2d');
new Chart(ctx, options);
Does anybody know how I can remove those unnecessary overlaying lines using Chart.js?
You can use the following chart plugin to remove those unnecessary overlaying lines :
Chart.plugins.register({
beforeDraw: function(chart) {
var ctx = chart.chart.ctx,
x_axis = chart.scales['x-axis-0'],
topY = chart.scales['y-axis-0'].top,
bottomY = chart.scales['y-axis-0'].bottom;
x_axis.options.gridLines.display = false;
x_axis.ticks.forEach(function(label, index) {
var x = x_axis.getPixelForValue(label);
ctx.save();
ctx.beginPath();
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.lineWidth = 1;
ctx.strokeStyle = x_axis.options.gridLines.color;
ctx.stroke();
ctx.restore();
});
}
});
ᴡᴏʀᴋɪɴɢ ᴅᴇᴍᴏ ⧩
Chart.plugins.register({
beforeDraw: function(chart) {
var ctx = chart.chart.ctx,
x_axis = chart.scales['x-axis-0'],
topY = chart.scales['y-axis-0'].top,
bottomY = chart.scales['y-axis-0'].bottom;
x_axis.options.gridLines.display = false;
x_axis.ticks.forEach(function(label, index) {
var x = x_axis.getPixelForValue(label);
ctx.save();
ctx.beginPath();
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.lineWidth = 1;
ctx.strokeStyle = x_axis.options.gridLines.color;
ctx.stroke();
ctx.restore();
});
}
});
var options = {
type: 'bar',
data: {
labels: ["1", "2", "3", "4", "5"],
datasets: [{
borderWidth: 2,
borderColor: "#5d5d5d",
pointBorderColor: "#5d5d5d",
pointBackgroundColor: "#5d5d5d",
pointBorderWidth: 5,
type: 'line',
data: [26, 26, 33, 28, 30],
fill: false,
lineTension: 0
}, {
borderWidth: 3,
pointBorderColor: "#b8b8b8",
pointBackgroundColor: "#b8b8b8",
pointBorderWidth: 10,
type: 'line',
data: [26, 26, 29, 28, 29],
fill: false,
lineTension: 0
}, {
data: [0, 0, 0, 0, 0],
fill: false,
lineTension: 0
}]
},
options: {
hover: {
mode: null
},
legend: {
display: false
},
tooltips: {
enabled: false
},
hover: {
mode: null
},
scales: {
xAxes: [{
gridLines: {
// drawBorder: false,
},
}],
yAxes: [{
display: false,
ticks: {
suggestedMin: 0,
max: 60,
beginAtZero: true
}
}]
}
}
}
var ctx = document.getElementById('canvas').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>

Categories

Resources