How to add "shadow" on hovering bar chart? - javascript

Is it possible to add some shadow while hovering an index in chartJS?
Somethink like in this answer which add a line when points are hovered but i would to use it with a bar chart and make it look something like this:
Here is my actual chart jsfiddle
<div class="chart-area chart-reparti">
<canvas id="chartReparti" width="1600" height="250"></canvas>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
var optionsReparti = {
maintainAspectRatio: false,
legend: {
display: true
},
tooltips: {
backgroundColor: '#f5f5f5',
titleFontColor: '#333',
bodyFontColor: '#666',
displayColors: true,
mode: 'index',
intersect: 0
},
responsive: true,
scales: {
yAxes: [{
id: 'importo',
gridLines: {
drawBorder: false,
borderDash: [4, 8],
color: 'rgba(0,132,255,0.4)',
},
ticks: {
beginAtZero: true,
userCallback: function (value, index, values) {
return "€" + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
}
}, {
id: 'qta',
gridLines: {
drawBorder: false,
borderDash: [4, 8],
color: 'rgba(247,136,0,0.4)',
},
ticks: {
beginAtZero: true
}
},
],
xAxes: [{
categoryPercentage: 1,
barPercentage: 0.4,
gridLines: {
drawBorder: false,
color: 'rgba(225,78,202,0.1)',
zeroLineColor: "transparent",
}
}]
}
};
var ctx = document.getElementById("chartReparti").getContext('2d');
var gradientImporto = ctx.createLinearGradient(0, 170, 0, 50);
gradientImporto.addColorStop(0, "rgba(0, 98, 255, 1)");
gradientImporto.addColorStop(1, "rgba(84, 150, 255, 1)");
var gradientQuantita = ctx.createLinearGradient(0, 170, 0, 50);
gradientQuantita.addColorStop(0, "rgba(247, 136, 0, 1)");
gradientQuantita.addColorStop(1, "rgba(255, 209, 72, 1)");
var chartReparti = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Cane', 'Gatto', 'Accessori', 'Mangime', 'Carne', 'Cane', 'Gatto', 'Accessori', 'Mangime', 'Carne'],
datasets: [{
label: "Quantità",
yAxisID: 'qta',
fill: true,
backgroundColor: gradientQuantita,
pointBackgroundColor: '#f78800',
data: [15, 15, 29, 10, 35, 12, 29, 10, 35, 12]
}, {
label: "Importo",
yAxesID: 'importo',
fill: true,
backgroundColor: gradientImporto,
pointBackgroundColor: '#0084ff',
data: [2954, 4564, 2954, 4564, 3456, 4212, 5060, 3456, 4212, 5060]
}
]
},
options: optionsReparti
});
Actually the code of the modified plugin got from this answer is not included as it wasn't working at all.

U can customize code before draw it
Working demo : https://jsfiddle.net/4rasm1hc/
let draw = Chart.controllers.line.prototype.draw;
Chart.controllers.line = Chart.controllers.bar.extend({
draw: function() {
draw.apply(this, arguments);
let ctx = this.chart.chart.ctx;
let _stroke = ctx.stroke;
ctx.stroke = function() {
ctx.save();
ctx.shadowColor = '#000000';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 4;
_stroke.apply(this, arguments)
ctx.restore();
}
}
});
Chart.defaults.LineWithLine = Chart.defaults.bar;
Chart.controllers.LineWithLine = Chart.controllers.bar.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+15,
topY =6000,
width=activePoint._view.width,
bottomY = 0;
console.log(activePoint);
// draw line
ctx.save();
ctx.beginPath();
ctx.moveTo(x, topY);
ctx.lineTo(x+width-10, bottomY+30);
ctx.lineWidth = width*4;
ctx.strokeStyle = '#e5e0e01a';
ctx.stroke();
ctx.restore();
}
}
});

Related

On click of legend, bar is hiding without issue but data value is not hiding in charts.js

I'm able to hide bar on legend click, but value is not hidden for bar chart in charts.js
I am not able to hide datavalues on click of legend, only bar is hidden
I have shared js fiddle code link below
Here, is the js fiddle
https://jsfiddle.net/npyvw1L8/
var ctx = document.getElementById("canvas").getContext("2d");
var nomi = \[2017, 2018, 2019\];
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: nomi,
datasets: \[{
label: 'PP PERVENUTI',
data: \[50, 30, 45\],
backgroundColor: "#8A0808",
fill: false,
borderColor: "#8A0808",
borderWidth: 3
},
{
label: 'PP EVASI',
data: \[60, 45, 12\],
backgroundColor: "#0B610B",
fill: false,
borderColor: "#0B610B",
borderWidth: 3
},
{
label: 'PI PERVENUTI',
data: \[20, 25, 35\],
backgroundColor: "#8A0886",
fill: false,
borderColor: "#8A0886",
borderWidth: 3
},
{
label: 'PI EVASI',
data: \[10, 20, 30\],
backgroundColor: "#0404B4",
fill: false,
borderColor: "#0404B4",
borderWidth: 3
}
\]
},
options: {
legend: {
display: true,
position: "bottom"
},
hover: {
animationDuration: 0
},
animation: {
onComplete: function() {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.fillStyle = "black";
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
debugger
this.data.datasets.forEach(function(dataset) {
for (var i = 0; i < dataset.data.length; i++) {
for (var key in dataset._meta) {
var model = dataset._meta\[key\].data\[i\]._model;
ctx.fillText(dataset.data\[i\], model.x, model.y - 5);
}
}
});
}
}
}
});
I am working on Vue and have implemented this chart, any help will be appreciated
You can get the meta info for that dataset and check if its hidden, if so skip that render loop:
var ctx = document.getElementById("canvas").getContext("2d");
var nomi = [2017, 2018, 2019];
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: nomi,
datasets: [{
label: 'PP PERVENUTI',
data: [50, 30, 45],
backgroundColor: "#8A0808",
fill: false,
borderColor: "#8A0808",
borderWidth: 3
},
{
label: 'PP EVASI',
data: [60, 45, 12],
backgroundColor: "#0B610B",
fill: false,
borderColor: "#0B610B",
borderWidth: 3
},
{
label: 'PI PERVENUTI',
data: [20, 25, 35],
backgroundColor: "#8A0886",
fill: false,
borderColor: "#8A0886",
borderWidth: 3
},
{
label: 'PI EVASI',
data: [10, 20, 30],
backgroundColor: "#0404B4",
fill: false,
borderColor: "#0404B4",
borderWidth: 3
}
]
},
options: {
legend: {
display: true,
position: "bottom"
},
hover: {
animationDuration: 0
},
animation: {
onComplete: function() {
var ctx = this.chart.ctx;
const chart = this.chart;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.fillStyle = "black";
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function(dataset, i) {
if (chart.getDatasetMeta(i).hidden) {
return;
}
for (var i = 0; i < dataset.data.length; i++) {
for (var key in dataset._meta) {
var model = dataset._meta[key].data[i]._model;
ctx.fillText(dataset.data[i], model.x, model.y - 5);
}
}
});
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<canvas id="canvas"></canvas>

Chart.js: refresh second Y axis step on legend click

My Chart.js plot uses two Y-Axis: both of them must have the same scale and max/min values. I update the second Y-Axis step depending on a boolean value I dinamically set and everything is working flawless. Still, I want to update the second Y-Axis (redrawn it) when I trigger a legend event (clicking on one of the legends). I can't really make it work: the plot refresh, but my second Y-Axis step doesn't change.
Here my draw function. I've read the Chart.js documentation I've found here, but I can really understand how to fill my legend onClick event.
function drawChart(pointsArray, curveFeatures) {
let minX = parseFloat(curveFeatures.minX);
let minY = parseFloat(curveFeatures.minY);
let maxX = parseFloat(curveFeatures.maxX);
let maxY = parseFloat(curveFeatures.maxY);
let stepResult = parseInt(curveFeatures.stepResult);
let startX = parseFloat(curveFeatures.startX);
let endX = parseFloat(curveFeatures.endX);
let upperLimit = parseFloat(curveFeatures.upperLimit);
let lowerLimit = parseFloat(curveFeatures.lowerLimit);
let stepSize;
let borderColour;
let backgroundColour;
if (stepResult === 1) {
stepSize = 0.5;
maxY = parseFloat(maxY.toFixed(2)) + stepSize;
minY = parseFloat(minY.toFixed(2)) - stepSize;
borderColour = "rgba(1, 165, 15, 1)";
backgroundColour = "rgba(1, 165, 15, 0.2)";
} else {
stepSize = 0.01;
maxY = parseFloat(maxY.toFixed(2));
minY = parseFloat(minY.toFixed(2));
borderColour = "rgba(252, 45, 45, 1)";
backgroundColour = "rgba(252, 45, 45, 0.2)";
}
let ctx = document.getElementById("myChart").getContext("2d");
let myChart = new Chart(ctx, {
type: "line",
data: {
datasets: [{
label: "Press Signal",
cubicInterpolationMode: "monotone",
fill: false,
borderWidth: 5,
radius: 1,
borderColor: borderColour,
backgroundColor: backgroundColour,
pointBorderColor: borderColour,
pointBackgroundColor: backgroundColour,
data: pointsArray
}, {
label: "Evaluation Windows",
cubicInterpolationMode: "monotone",
fill: true,
borderWidth: 2,
radius: 2,
borderColor: "rgb(94, 233, 255, 1)",
backgroundColor: "rgb(94, 233, 255, 0.2)",
pointBorderColor: "rgb(94, 233, 255, 1)",
pointBackgroundColor: "rgb(94, 233, 255, 0.2)",
data: [{
x: startX,
y: lowerLimit
}, {
x: startX,
y: upperLimit
}, {
x: endX,
y: upperLimit
}, {
x: endX,
y: lowerLimit
}, {
x: startX,
y: lowerLimit
}]
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
animation: {
duration: 2000
},
layout: {
padding: {
left: 50,
right: 50,
top: 50,
bottom: 10
}
},
title: {
display: true,
text: "Press Signal",
fontSize: 30,
padding: 20
},
legend: {
labels: {
fontSize: 16
},
onClick: function(e, legendItem) {
stepSize = 0.01;
// Should I do things, here?
ci.update();
}
},
scales: {
xAxes: [{
display: true,
type: "linear",
position: "bottom",
ticks: {
fontSize: 14,
},
scaleLabel: {
display: true,
fontSize: 16,
fontColor: "black",
labelString: "Position (Abs.) [mm]"
}
}],
yAxes: [{
display: true,
type: "linear",
position: "left",
ticks: {
fontSize: 14,
},
scaleLabel: {
display: true,
fontSize: 16,
fontColor: "black",
labelString: "Force [kN]"
}
}, {
display: true,
type: "linear",
position: "right",
ticks: {
fontSize: 14,
beginAtZero: false,
max: maxY,
min: minY,
stepSize: stepSize
},
afterTickToLabelConversion: function(scaleInstance) {
if (stepResult === 1) {
// set the first and last tick to null so it does not display
// note, ticks[0] is the last tick and ticks[length - 1] is the first
scaleInstance.ticks[0] = null;
scaleInstance.ticks[scaleInstance.ticks.length - 1] = null;
// need to do the same thing for this similiar array which is used internally
scaleInstance.ticksAsNumbers[0] = null;
scaleInstance.ticksAsNumbers[scaleInstance.ticksAsNumbers.length - 1] = null;
}
}
}]
}
}
});
}
I've found my way. Here a snippet for whoever will have my same problem:
onClick: function(event, legendItem) {
let index = 1;
myChart.data.datasets[index].hidden = !myChart.data.datasets[index].hidden;
if (myChart.data.datasets[index].hidden) {
myChart.options.scales.yAxes[index].ticks.max = maxY;
myChart.options.scales.yAxes[index].ticks.min = minY;
myChart.options.scales.yAxes[index].ticks.stepSize = stepSize;
} else {
if (stepResult === 0) {
myChart.options.scales.yAxes[index].ticks.max = 3.5;
myChart.options.scales.yAxes[index].ticks.min = 0;
myChart.options.scales.yAxes[index].ticks.stepSize = 0.5;
}
}
myChart.update();
}

Chart js vertical line z-index

I want to change the behaviour of my vertical line in my chart js. Currently vertical line is on top of my points and hover points: i want it to be behind. My code setup posted below. Also this line is drawn on hover. So i want to only change z-index of vertical line. this line has z-index if so how can i target it?
my code
var ctx = document.getElementById('chart').getContext("2d");
var gradientStroke = ctx.createLinearGradient(1000, 1000, 1000, 0);
gradientStroke.addColorStop(1, "rgb(33, 240, 43)");
gradientStroke.addColorStop(0.25, "rgb(21, 168, 226)");
gradientStroke.addColorStop(0.5, "rgb(21, 168, 226)");
gradientStroke.addColorStop(0, "rgb(14, 144, 177)");
var data = {
legend: false,
labels: ["02 FEB", "03 FEB", "04 FEB", "05 FEB", "06 FEB", "07 FEB", "08 FEB", "09 FEB", "10 FEB", "11 FEB", "12 FEB"],
datasets: [{
fill: false,
backgroundColor: gradientStroke,
borderColor: gradientStroke,
borderWidth: 4,
data: [9412, 17000, 18000, 11000, 9254, 7200, 11600, 15644, 11222, 13333, 12545],
pointBorderWidth: 9,
pointRadius: 9,
pointBorderColor: 'transparent',
pointHoverRadius: 8,
pointHoverBorderWidth: 3,
pointHoverBackgroundColor: '#27f327',
pointHoverBorderColor: 'white',
pointBackgroundColor: 'transparent'
}]
};
var options = {
hover: {
mode: 'index',
intersect: true
},
tooltips: {
backgroundColor: '#FFF',
bodyFontColor: '#393f5b',
bodyFontSize: 20,
displayColors: false,
bodySpacing: 10,
intersect: false,
bodyFontStyle: 'bold',
xPadding: 15,
yPadding: 15,
mode: 'index',
callbacks: {
title: function() {}
}
},
legend: {
display: false
},
maintainAspectRatio: false,
scales: {
yAxes: [{
stacked: true,
gridLines: {
display: true,
color: "#6e6e6e26",
padding: 0,
},
ticks: {
beginAtZero: true,
min: 0,
max: 20000,
stepSize: 5000,
display: false
}
}],
xAxes: [{
gridLines: {
display: false,
color: "#6e6e6e26",
},
ticks: {
fontSize: 14,
fontColor: '#afb6d4',
}
}]
}
};
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 = '#4b4b4b8e';
ctx.shadowBlur = 20;
ctx.shadowOffsetX = 1;
ctx.shadowOffsetY = 2;
_stroke.apply(this, arguments);
ctx.restore();
}
};
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 = '#000';
ctx.shadowBlur = 1;
ctx.stroke();
ctx.restore();
}
}
});
var chart = new Chart(ctx, {
type: 'LineWithLine',
data: data,
options: options
});
Move Chart.controllers.line.prototype.draw.call(this, ease); after vertical line drawing:
var ctx = document.getElementById('chart').getContext("2d");
var gradientStroke = ctx.createLinearGradient(1000, 1000, 1000, 0);
gradientStroke.addColorStop(1, "rgb(33, 240, 43)");
gradientStroke.addColorStop(0.25, "rgb(21, 168, 226)");
gradientStroke.addColorStop(0.5, "rgb(21, 168, 226)");
gradientStroke.addColorStop(0, "rgb(14, 144, 177)");
var data = {
legend: false,
labels: ["02 FEB", "03 FEB", "04 FEB", "05 FEB", "06 FEB", "07 FEB", "08 FEB", "09 FEB", "10 FEB", "11 FEB", "12 FEB"],
datasets: [{
fill: false,
backgroundColor: gradientStroke,
borderColor: gradientStroke,
borderWidth: 4,
data: [9412, 17000, 18000, 11000, 9254, 7200, 11600, 15644, 11222, 13333, 12545],
pointBorderWidth: 9,
pointRadius: 9,
pointBorderColor: 'transparent',
pointHoverRadius: 8,
pointHoverBorderWidth: 3,
pointHoverBackgroundColor: '#27f327',
pointHoverBorderColor: 'white',
pointBackgroundColor: 'transparent'
}]
};
var options = {
hover: {
mode: 'index',
intersect: true
},
tooltips: {
backgroundColor: '#FFF',
bodyFontColor: '#393f5b',
bodyFontSize: 20,
displayColors: false,
bodySpacing: 10,
intersect: false,
bodyFontStyle: 'bold',
xPadding: 15,
yPadding: 15,
mode: 'index',
callbacks: {
title: function() {}
}
},
legend: {
display: false
},
maintainAspectRatio: false,
scales: {
yAxes: [{
stacked: true,
gridLines: {
display: true,
color: "#6e6e6e26",
padding: 0,
},
ticks: {
beginAtZero: true,
min: 0,
max: 20000,
stepSize: 5000,
display: false
}
}],
xAxes: [{
gridLines: {
display: false,
color: "#6e6e6e26",
},
ticks: {
fontSize: 14,
fontColor: '#afb6d4',
}
}]
}
};
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 = '#4b4b4b8e';
ctx.shadowBlur = 20;
ctx.shadowOffsetX = 1;
ctx.shadowOffsetY = 2;
_stroke.apply(this, arguments);
ctx.restore();
}
};
Chart.defaults.LineWithLine = Chart.defaults.line;
Chart.controllers.LineWithLine = Chart.controllers.line.extend({
draw: function(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 = '#000';
ctx.shadowBlur = 1;
ctx.stroke();
ctx.restore();
}
Chart.controllers.line.prototype.draw.call(this, ease);
}
});
var chart = new Chart(ctx, {
type: 'LineWithLine',
data: data,
options: options
});
#chart {
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<canvas id="chart"></canvas>

How to add a vertical line on Chart.js when hover a point?

I've created a chart by using Chart.js. It displays some currency values on horizontal and vertical axes. I added many points and I show them as circle. I want to add a vertical line on the point when hover on the point like this:
And here is my chart code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script>
<div class="container" style="width: 100%;margin-top:30px;">
<canvas id="myChart"></canvas>
</div>
<script>
let zzz = document.getElementById('myChart').getContext('2d');
// Global Options
Chart.defaults.global.defaultFontFamily = 'Arial';
Chart.defaults.global.defaultFontSize = 16;
Chart.defaults.global.defaultFontColor = '#000';
let massPopChart = new Chart(zzz, {
type:'line',
data:{
labels:[
'20/09/2017',
'20/10/2017',
'20/11/2017',
'20/12/2017'
],
datasets:[{
label:'US Dollar',
fill: false,
lineTension: 0,
data:[
123,
143,
156,
122
],
pointBackgroundColor: '#f90',
pointHoverBackgroundColor: '#fff',
//backgroundColor:'green',
backgroundColor:[
'#2277bb',
'#2277bb',
'#2277bb',
'#000000',
],
borderWidth:3,
borderColor:'#f90',
hoverBorderWidth:3,
hoverBorderColor:'#fff'
}]
},
options:{
title:{
display:true,
text:'Chart 1',
fontSize:16
},
legend:{
display:true,
position:'top',
labels:{
fontColor:'#000'
}
},
layout:{
padding:{
left:50,
right:0,
bottom:0,
top:0
}
},
tooltips:{
enabled:true,
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
elements: {
point: {
radius: 5
}
},
}
});
</script>
And how can I add a line to my chart like in the example above?
I found another question that describes the solution you want. I hope this helps.
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 = 4;
ctx.strokeStyle = '#757575';
ctx.stroke();
ctx.restore();
}
}
});
Chart.defaults.global.defaultFontFamily = 'Arial';
Chart.defaults.global.defaultFontSize = 16;
Chart.defaults.global.defaultFontColor = '#000';
var chart = new Chart("myChart", {
type: 'LineWithLine',
data: {
labels: ['20/09/2017',
'20/10/2017',
'20/11/2017',
'20/12/2017'
],
datasets: [{
label: 'US Dollar',
fill: false,
lineTension: 0,
data: [123, 143, 156, 122],
pointBackgroundColor: '#f90',
pointHoverBackgroundColor: '#fff',
//backgroundColor:'green',
backgroundColor: ['#2277bb', '#2277bb', '#2277bb', '#000000', ],
borderWidth: 3,
borderColor: '#f90',
hoverBorderWidth: 3,
hoverBorderColor: '#fff'
}]
},
options: {
title: {
display: true,
text: 'Chart 1',
fontSize: 16
},
legend: {
display: true,
position: 'top',
labels: {
fontColor: '#000'
}
},
layout: {
padding: {
left: 50,
right: 0,
bottom: 0,
top: 0
}
},
tooltips: {
enabled: true,
intersect: false
},
elements: {
point: {
radius: 5
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" style="width: 100%;margin-top:30px;">
<canvas id="myChart"></canvas>
</div>

Chart.js - change starting position of scale/line

So I'm using Chart.js to plot a graph on my web app,
What I'm trying to achieve is to control the starting point of the graph itself, so I could control where the scales are located
This is what I have so far:
Eventually, I'm trying to make the scale appear at the center of each "stripe".
I've seen in the documentation that you can extend scales and charts to customize it to your own needs but I tried fiddling with it with no success regarding what I need.
This is an example of what I'm trying to achieve:
Code:
var type = 'line';
var daysArray = new Array(30).join().split(',').map(function (item, index) { ++index; return (index % 5 == 0 || index == 1) ? index : '' })
var data = {
labels: this.daysArray,
datasets: [{
borderColor: "#707bbb",
showLine: false,
fill: false,
pointBackgroundColor: "#707bbb",
pointRadius: 3,
data: [65, 59, 80, 81, 56, 20, 32, 65, 59, 80, 81, 56, 20, 32]
},
{
borderColor: "#2972c5",
borderWidth: 1,
fill: false,
pointRadius: 0,
data: [102, 42, 36, 98, 15, 15, 19, 65, 59, 80, 81, 56, 20, 32]
}
]
};
var options = {
bezierCurve: false,
responsive: true,
maintainAspectRatio: false,
display: false,
scales: {
yAxes: [{
display: false
}],
xAxes: [{
gridLines: {
drawOnChartArea: true,
drawBorder: false
},
ticks: {
fontStyle: "normal",
maxRotation: 0,
labelOffset: 1
}
}]
},
legend: {
display: false
}
};
Chart.pluginService.register({
beforeDatasetsDraw: function (chart, easing) {
if (chart.chartArea) {
var noOfLabels = chart.chart.config.data.labels.length;
var helpers = Chart.helpers;
var ctx = chart.chart.ctx;
//
ctx.save();
var chartArea = chart.chartArea;
var chartWidth = chartArea.right - chartArea.left;
var chartHeight = Math.abs(chartArea.top - chartArea.bottom);
var stripWidth = chartWidth / noOfLabels;
var pattern = document.createElement('canvas');
pattern.width = stripWidth * 2;
pattern.height = chartHeight;
var pctx = pattern.getContext('2d');
pctx.fillStyle = "#f0f2f5";
pctx.fillRect(0, 0, stripWidth, chartHeight);
pctx.fillStyle = "#ffffff";
pctx.fillRect(stripWidth, 0, stripWidth, chartHeight);
var ptr = ctx.createPattern(pattern, "repeat");
ctx.fillStyle = ptr;
ctx.fillRect(chartArea.left, chartArea.top, chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
ctx.restore();
ctx.save();
}
},
});
Chart.scaleService.getScaleConstructor("category").extend({
margins: {
left: 100
},
paddingLeft: 300
});
this.chart = new Chart(document.querySelector('canvas'), {
type: type,
data: data,
options: options
});
The code is a bit messy because I tried playing with some options and thought I would leave it just there
Anyone has an idea what to do?

Categories