ChartJS Draw grid line X-Axis and Y-Axis - chart.js

I'm trying out chart.js for the first time. It has an option to show or hide vertical or horizontal grid lines i.e. scaleShowHorizontalLines: true/false or scaleShowVerticalLines: true/false. But it doesn't draw grid line on the actual x-axis or y-axis. How would I go about drawing the grid line for the x-axis or the y-axis?

But it doesn't draw grid line on the actual x-axis or y-axis.
Setting scaleShowHorizontalLines or scaleShowVerticalLines doesn't hide the x or y axis.
However if you do want to hide it (or make it visible) without hiding the scale labels, you can do
var myChart = new Chart(ctx).Line(data, {
scaleLineColor: 'rgba(0, 0, 0, 0)',
...
to hide the axes. Or to override any global configuration and show the axes (you can put in any color).
var myChart = new Chart(ctx).Line(data, {
scaleLineColor: 'rgba(0, 0, 0, 1)',
...
If you are not seeing the x and y axis AND their labels, you probably have showScale globally configured false
var myChart = new Chart(ctx).Line(data, {
showScale: true,
...
Drawing Only the X Axis without the Y Axis
If you want to draw the x axis and not the y axis, you have to hide both and draw the x axis yourself, like so
Chart.types.Bar.extend({
name: "BarAlt",
intialize: function () {
Chart.types.Bar.intialize.draw.apply(this, arguments);
},
draw: function () {
Chart.types.Bar.prototype.draw.apply(this, arguments);
var ctx = this.chart.ctx;
ctx.save();
ctx.lineWidth = this.scale.lineWidth;
ctx.strokeStyle = 'white';
ctx.beginPath();
ctx.moveTo(this.scale.xScalePaddingLeft, this.scale.calculateY(0));
ctx.lineTo(this.chart.width, this.scale.calculateY(0));
ctx.stroke();
ctx.closePath();
ctx.restore();
}
});
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(254, 164, 0, 1)",
strokeColor: "rgba(254, 164, 0, 1)",
highlightFill: "rgba(254, 164, 0, 1)",
highlightStroke: "rgba(254, 164, 0, 1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx).BarAlt(data, {
scaleFontColor: '#fff',
scaleGridLineColor: 'rgba(255, 255, 255, 0.4)',
scaleLineColor: 'rgba(0, 0, 0, 0)',
scaleShowVerticalLines: false
});

Related

Fill color to pointer in Chartjs

I'm using scatter graph. On hover over a point, the box representing the point color is not filled
I need to fill it with the color of the line instead of just the border being of the color.
Fiddle
This is my dataset:
this.ScatterChart.data.datasets.push({
label: this.label,
data: this.Axiscoordinates,
fill: false,
lineTension: 0.1,
borderColor: SetColor,
color: SetColor,
backGroundColor: SetColor,
borderWidth: 1,
yAxisID: this.yAxisUnit,
showLine: true
});
in your dataset object put the backgroundColor to the color you want it to be, that will solve it
datasets: [
{
data: []
backgroundColor: color
}
]
EDIT:My mistake backgroundColor is with a lower g instead of a captial one

chartjs display crosshair onHover

https://codepen.io/qkreltms/pen/BaaWZeV?editors=0010
I've tried making crosshair when hover on points:
But there are some bugs
Crosshair appears when mouse hover on the almost exactly middle on the points, not any position on points.
Crosshair border keeps thicker when mouse points moves middle on the points.
Any ideas?
Code :
var ctx = document.getElementById("myChart").getContext("2d");
const colors = {
darkBlue: {
fill: '#92bed2',
stroke: '#3282bf',
},
purple: {
fill: '#8fa8c8',
stroke: '#75539e',
}
};
const test = [5, 9, 10, 9, 18, 19, 20];
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: test,
datasets: [{
label: "Unavailable",
fill: true,
backgroundColor: colors.purple.fill,
pointBackgroundColor: colors.purple.stroke,
borderColor: colors.purple.stroke,
pointHighlightStroke: colors.purple.stroke,
borderCapStyle: 'butt',
data: test,
}]
},
options: {
onHover: function(event) {
const chart = myChart.getElementAtEvent(event)[0]._chart;
const activeElements = myChart.getElementsAtEvent(event);
console.log(chart)
if (activeElements.length) {
const activePoint = activeElements[0];
const ctx = chart.ctx;
if (!ctx) {
return;
}
const x = activePoint._view.x;
const y = activePoint._view.y;
const leftX = chart.chartArea.left;
const topY = chart.chartArea.top;
const RightX = chart.chartArea.right;
const bottomY = chart.chartArea.bottom;
ctx.beginPath();
// ctx.setLineDash([5, 15]);
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.moveTo(leftX, y);
ctx.lineTo(RightX, y);
ctx.lineWidth = 1;
ctx.strokeStyle = "#C2C7CC";
ctx.stroke();
ctx.closePath();
}
},
responsive: false,
scales: {
},
animation: {
duration: 750,
},
}
});

Display Chartjs tooltip values outside the canvas - multi line chart

I am trying to replicate the NSE Stock exchange comparison graph as displayed here.
I am using Chartjs 2.0. I have 2 line graphs in the chart.
On hovering on the data points I want to show the tooltip's ylabel in a div which is outside the canvas, (like the changing values are displayed in the top right corner in the chart above)
I found GRUNT's code helpful
Moving vertical line when hovering over the chart using chart.js
You can use Label Callback
document.getElementById('y-label').textContent = tooltipItem.yLabel;
Chart.defaults.LineWithLine = Chart.defaults.line;
Chart.controllers.LineWithLine = Chart.controllers.line.extend({
draw: function(ease) {
Chart.controllers.line.prototype.draw.call(this, ease);
if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
var activePoint = this.chart.tooltip._active[0],
ctx = this.chart.ctx,
x = activePoint.tooltipPosition().x,
topY = this.chart.scales['y-axis-0'].top,
bottomY = this.chart.scales['y-axis-0'].bottom;
// draw line
ctx.save();
ctx.beginPath();
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.lineWidth = 2;
ctx.strokeStyle = '#07C';
ctx.stroke();
ctx.restore();
}
}
});
var chart = new Chart(ctx, {
type: 'LineWithLine',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'],
datasets: [{
label: 'Statistics',
data: [3, 1, 2, 5, 4, 7, 6],
backgroundColor: 'rgba(0, 119, 204, 0.8)',
borderColor: 'rgba(0, 119, 204, 0.3)',
fill: false
}]
},
options: {
responsive: false,
tooltips: {
intersect: false,
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += Math.round(tooltipItem.yLabel * 100) / 100;
document.getElementById('y-label').textContent = tooltipItem.yLabel;
return label;
}
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<h4 id="y-label"> </h4>
<canvas id="ctx" height="200"></canvas>

Chart JS data labels getting cut

I am using Chart JS with data label plugin and I want to show data labels next to the bar and pie chart but noticed that some of the data labels are getting cut or going out of canvas. Is their any way to fix this?
var chartData3 = {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [{
backgroundColor: "#79D1CF",
data: [60, 90, 81, 56, 55, 40],
datalabels: {
align: 'end',
anchor: 'end'
}
}]
};
https://plnkr.co/edit/I906pCN8tdrrOX2hgN0W?p=preview
Thanks,
MSK
You need to set padding to display the labels properly. Also, adjust the canvas width and height to account for padding so that your chart doesn't get too small.
options: {
layout: {
padding: {
left: 50,
right: 50,
top: 50,
bottom: 50
}
}
}
Set max tick in chart option, for example:
this.chartOption.scales.yAxes[0].ticks.max = Math.max(...chartData3.datasets[0].data) * 1.2

Chartjs How to render a custom horizon line under X-Axis

I am working ChartJS component using angular2. I would like to know whether there is any way to render as this image or not.
Basically, The Bar Chart rendered on the grid. When I click on the column bar, for example, June the horizontal line should be displayed with the up arrow at the exact month under the column bar. Do you have any suggestions? Thanks in advance.
You can capture the onclick event of the canvas and check which bar has been clicked with the getElementAtEvent method of chartjs. getElementAtEvent gives you all the relevant information you need (chart-width, x-coordinate of the bar, label etc.) to draw a custom line below the chart.
canvas.onclick = function (evt) {
var activePoints = myBarChart.getElementAtEvent(evt);
if (activePoints[0]) {
//draw your custom line
}
};
The snippet below has two canvas. One for chart.js to draw the actual chart and the second below to draw a line with the text of the clicked label.
var canvas = document.getElementById('myChart');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 20, 81, 56, 55, 40],
}]
};
var option = {
scales: {
yAxes: [{
stacked: true,
gridLines: {
display: true,
color: "rgba(255,99,132,0.2)"
}
}],
xAxes: [{
gridLines: {
display: false
}
}]
}
};
var myBarChart = Chart.Bar(canvas, {
data: data,
options: option
});
canvas.onclick = function (evt) {
var activePoints = myBarChart.getElementAtEvent(evt);
if (activePoints[0]) {
var chart = activePoints[0]._chart;
var canvasX = document.getElementById('xAxis2');
// set the width of the second canvas to the chart width
canvasX.width = chart.width;
var canvas2D = canvasX.getContext('2d');
// draw the line
canvas2D.moveTo(0, 20);
canvas2D.lineTo(activePoints[0]._view.x - 10, 20);
canvas2D.lineTo(activePoints[0]._view.x, 0);
canvas2D.lineTo(activePoints[0]._view.x + 10, 20);
canvas2D.lineTo(canvasX.width, 20);
canvas2D.stroke();
// add the label text
canvas2D.font = '12px serif';
canvas2D.fillText('for ' + activePoints[0]._view.label, canvasX.width - 100, 15);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>
<canvas id="xAxis2" height="20"></canvas>