Can't display proper time on chart.js timeline - javascript

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);

Related

Chart.js - How to customize specific grid line depending on tick value

I have a radar chart in which "100" represents the global average value for a characteristic.
To make the chart more readable I want to make only the grid line that indicates the 100 value mark dashed.
Is there a way to do this?
Current chart code is here: jsfiddle.
const config = {
type: 'radar',
data: data,
options: {
elements: {
line: {
borderWidth: 3
},
point: {
pointRadius: 5
}
},
scales: {
r: {
angleLines: {
lineWidth: 2
},
grid: {
circular: true,
lineWidth: 2
}
}
}
}
};
In my opinion, the logically correct answer is to define grid.borderDash as follows:
grid: {
...
borderDash: ctx => ctx.tick.value == 100 ? [8, 4] : []
},
To make it work however, I had to use ctx.tick.value == 95 (This could be a bug in Chart.js). Please take a look at your amended code and see how it works.
let dataValues = [100, 120, 80, 100, 90, 110, 100, 100, 100]
const sum = dataValues.reduce((a, b) => a + b, 0);
const avg = sum / dataValues.length;
const sorted = [...dataValues].sort(function(a, b) {
return a - b;
});
const data = {
labels: dataValues.map((v, i) => 'Signal ' + (i + 1)),
datasets: [{
label: '9 signals',
data: dataValues,
fill: true,
backgroundColor: 'rgba(210, 203, 203, 0.4)',
borderColor: 'rgb(210, 203, 203, 0.6)',
pointBackgroundColor: function(context) {
var index = context.dataIndex;
var value = context.dataset.data[index];
return value < sorted[3] ? 'blue' :
value < sorted[5] ? 'green' :
value < sorted[7] ? 'orange' :
'red';
},
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(255, 99, 132)'
}
]
};
const config = {
type: 'radar',
data: data,
options: {
elements: {
line: {
borderWidth: 3
},
point: {
pointRadius: 5
}
},
scales: {
r: {
suggestedMin: 70,
angleLines: {
lineWidth: 2
},
grid: {
circular: true,
lineWidth: 2,
borderDash: ctx => ctx.tick.value == 95 ? [8, 4] : []
},
ticks: {
stepSize: 5
}
}
}
}
};
let myChart = new Chart('myChart',
config
);
.chartBox {
width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<div class="chartBox">
<canvas id="myChart"></canvas>
</div>

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>

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

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>

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