Chart.js - Add gradient to bar chart - javascript

I am looking to build a chart like this
But I am not able to give the gradient colors in the y-scale for the bar chart. This is the codesandbox URL.

The gradient direction (Vertically in your case) not related directly to chart.js, but to HTML canvas createLinearGradient() Method.
createLinearGradient JavaScript syntax:
context.createLinearGradient(x0,y0,x1,y1);
https://www.w3schools.com/tags/canvas_createlineargradient.asp
Example of top to bottom "vertically" gradient from w3schools:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var my_gradient = ctx.createLinearGradient(0, 0, 0, 170);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(1, "white");
ctx.fillStyle = my_gradient;
ctx.fillRect(20, 20, 150, 100);
<div>Top to bottom</div>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
"One gradient"
Docs:
An alternative option is to pass a CanvasPattern or CanvasGradient
object instead of a string colour. https://www.chartjs.org/docs/latest/general/colors.html#patterns-and-gradients
Same as one solid color but passing CanvasGradient object:
var bar_ctx = document.getElementById('chart').getContext('2d');
var background_1 = bar_ctx.createLinearGradient(0, 0, 0, 600);
background_1.addColorStop(0, 'red');
background_1.addColorStop(1, 'blue');
And set background_1 under data
/* data */
var data = {
labels: ["Africa", "Asia", "Europe", "America"],
datasets: [{
/* data */
label: "Population (millions)",
backgroundColor: background_1,
data: [40,60,80, 100]
}]
};
"multiple colors for bars"
Use multiple gradients objects inside backgroundColor (object1 for item-1 and so on).
backgroundColor: [background_1, background_2, background_3, background_4],
** My code is not DRY (The best idea her is to create gradient objects by some loop throw array of data). By purpose i keep this example "simple".
var bar_ctx = document.getElementById('chart').getContext('2d');
var background_1 = bar_ctx.createLinearGradient(0, 0, 0, 600);
background_1.addColorStop(0, 'red');
background_1.addColorStop(1, 'blue');
var background_2 = bar_ctx.createLinearGradient(0, 0, 0, 600);
background_2.addColorStop(0, 'green');
background_2.addColorStop(1, 'orange');
var background_3 = bar_ctx.createLinearGradient(0, 0, 0, 600);
background_3.addColorStop(0, 'orange');
background_3.addColorStop(1, 'purple');
var background_4 = bar_ctx.createLinearGradient(0, 0, 0, 600);
background_4.addColorStop(0, 'green');
background_4.addColorStop(1, 'violet');
/* data */
var data = {
labels: ["Africa", "Asia", "Europe", "America"],
datasets: [{
/* data */
label: "Population (millions)",
backgroundColor: [background_1, background_2, background_3, background_4],
data: [40,60,80, 100]
}]
};
var options = {
responsive: true,
title: {
text: 'multiple colors for bars',
display: true
},
scales: {
xAxes: [{
stacked: true,
ticks: {
},
}],
yAxes: [{
stacked: true,
}]
}
};
var myChart = new Chart(document.getElementById("chart"), {
type: 'bar',
data: data,
options: options
});
<canvas id="chart" width="800" height="600"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>

Try to click one of the jsfiddle there, then change the chart type to 'bar'. You'll see it will work.
Yes they are all the same color, because on their example they are only using one gradient. You can create multiple gradient with different color and apply it seperately since you are using multiple rgba already, you can change it and apply specific gradient to your bar. My english is not that good i hope you get my point.

Related

Chart JS tick options not working for y axis

I have been struggling to make a chart.js line chart start at 0 when all of the values are 0. If all of the data of a dataset is 0 the y axis will always show values below 0 which I don't want there.
Here is the example:
<div class="container">
<canvas id="lineChart"></canvas>
<script>
var ctx = document.getElementById('lineChart');
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: [1,2,3],
datasets: [{
data: [0, 0, 0]
}]
},
options: {
responsive: true,
scales: {
y: {
ticks: {
beginAtZero:true
}
}
}
}
});
</script>
<div>
As you can see I am changing the options the scales as suggested in the documentation here (apparently there has been migration and this is the way to go in v3, which is what I am using). But the graph still won't start at 0:
Any axis options other than the ticks work correctly.
Any ideas of what I might be doing wrong?
You tried to place the beginAtZero in the V2 place, in V3 you have to put it in the root of the scale object like so:
const options = {
type: 'line',
data: {
labels: [1, 2, 3],
datasets: [{
label: '# of Votes',
data: [0, 0, 0],
borderColor: 'pink'
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
}
const 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>
For all changes between V2 and V3 you can read the migration guide

ChartJS - Moving vertical line is display on top of tooltip

Hello,
I've followed this post (Moving vertical line when hovering over the chart using chart.js) to draw a vertical line on my chart.
With a single dataset, it's working just fine.
But for a multiple datasets display (with stacked options on the y-axis), the vertical line is drawn over the chart's tooltip.
Neither setting the z-index of the chart's tooltip nor the vertical line could solve my problem. Since I can't find any property to do that.
Do you have any idea/suggestion to solve this issue?
I'm using react-chart-js 2 with chart-js ^2.9.4 as a peer dependency.
You can use a custom plugin that draws after all the datasets have drawn but before the tooltip is drawn:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
stacked: true
}]
},
plugins: {
customLine: {
width: 5,
color: 'pink'
}
}
},
plugins: [{
id: 'customLine',
afterDatasetsDraw: (chart, x, opts) => {
const width = opts.width || 1;
const color = opts.color || 'black'
if (!chart.active || chart.active.length === 0) {
return;
}
const {
chartArea: {
top,
bottom
}
} = chart;
const xValue = chart.active[0]._model.x
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(xValue, top);
ctx.lineTo(xValue, bottom);
ctx.stroke();
}
}]
}
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/2.9.4/Chart.js"></script>
</body>

How do I remove cartesian axes from chart js?

I am trying to personalize a chart.js. But I can not find how to remove (or hide) the X and Y axes.
I am also interested in not showing data on hover and I would like not to show the reference on the top. I am just starting with chart.js and I only need to do a few graphs.
Thank you :)
This is the graph I currently have
datasets: {
label: "I need help plz",
backgroundColor: gradient,
fill: true,
borderColor: "rgb(0, 50, 100)",
borderWidth: 0.001,
tension: 0.4,
radius: 0,
data: dataset,
},
For removing the references on the top this post was useful Chart.js v2 hide dataset labels
As described in the documentation (https://www.chartjs.org/docs/master/axes/#common-options-to-all-axes) you can set in the options of the scale the display to true or false or 'auto' where auto hides the scale if no dataset is visable that is linked to that axis.
For not showing data on hover you can set the tooltip to enabled: false
Example (y auto display and no x axis):
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1,
backgroundColor: 'red'
}, ]
},
options: {
plugins: {
tooltip: {
enabled: false
}
},
scales: {
y: {
display: 'auto'
},
x: {
display: false
}
}
}
}
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.3.2/chart.js"></script>
</body>

ChartJS xAxis label position

I have a ChartJS that display the label as slanted when you resize the window to smaller size.
What I want to do is to lower the X-labels down a bit vertically so they are not as close to the base of the graph if possible.
After googling around, it looks like I can disable the tick display for x-Axis and use the option's animation to do this manually. I tried to implement this in the following fiddle.
animation: {
duration: 1,
onComplete: function() {
var chartInstance = this.chart;
this.data.datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
var label = bar._model.label;
var xOffset = bar._model.x;
var yOffset = bar._model.y;
ctx.fillText(label, xOffset, 420);
});
});
}
},
However, I can't get the label to scale properly when I resize the window. Can you help?
Chart.js implements a padding property in the ticks object for this:
Padding between the tick label and the axis. When set on a vertical axis, this applies in the horizontal (X) direction. When set on a horizontal axis, this applies in the vertical (Y) direction.
Here's a working example with the x-axis labels offset 20px down from the line:
new Chart(document.getElementById("chart"), {
type: "bar",
data: {
labels: ["Blue", "Red", "Green", "Orange", "Purple"],
datasets: [{
data: [0, 1, 2, 3, 4]
}]
},
options: {
maintainAspectRatio: false,
scales: {
xAxes: [{
ticks: {
padding: 20
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<div style="height:200px;width:200px">
<canvas id="chart"></canvas>
</div>

Chart area background color chartjs

I have problem with chart js, i want to coloring chart area like image above
I try to find configuration from charJs Docs , but nothing matched.
its possible or not to change chart area background color?
if possible anyone can help me?
Html
<canvas id="barChart" width="600" height="300"></canvas>
Javascript
var ctx = document.getElementById("barChart");
var barChart = new Chart(ctx,{
type: 'bar',
data: {
labels:["Label1","Label2","Label3","Label4"],
borderColor : "#fffff",
datasets: [
{
data: ["2","3","1","4"],
borderColor : "#fff",
borderWidth : "3",
hoverBorderColor : "#000",
backgroundColor: [
"#f38b4a",
"#56d798",
"#ff8397",
"#6970d5"
],
hoverBackgroundColor: [
"#f38b4a",
"#56d798",
"#ff8397",
"#6970d5"
]
}]
},
options: {
scales: {
yAxes: [{
ticks:{
min : 0,
stepSize : 1,
fontColor : "#000",
fontSize : 14
},
gridLines:{
color: "#000",
lineWidth:2,
zeroLineColor :"#000",
zeroLineWidth : 2
},
stacked: true
}],
xAxes: [{
ticks:{
fontColor : "#000",
fontSize : 14
},
gridLines:{
color: "#fff",
lineWidth:2
}
}]
},
responsive:false
}
});
Here's my current code jsFiddle
so everyone can try for find solution.
thanks for your help.
There is no built-in method to change background color, but you can use CSS. JSFiddle.
ctx.style.backgroundColor = 'rgba(255,0,0,255)';
EDIT
If you want to fill exact area of chart and no whole div, you can write your own chart.js plugin. Try it on JSFiddle.
Chart.pluginService.register({
beforeDraw: function (chart, easing) {
if (chart.config.options.chartArea && chart.config.options.chartArea.backgroundColor) {
var ctx = chart.chart.ctx;
var chartArea = chart.chartArea;
ctx.save();
ctx.fillStyle = chart.config.options.chartArea.backgroundColor;
ctx.fillRect(chartArea.left, chartArea.top, chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
ctx.restore();
}
}
});
var config = {
type: 'bar',
data: {
labels:["Label1","Label2","Label3","Label4"],
borderColor : "#fffff",
datasets: [
{
data: ["2","3","1","4"],
borderColor : "#fff",
borderWidth : "3",
hoverBorderColor : "#000",
backgroundColor: [
"#f38b4a",
"#56d798",
"#ff8397",
"#6970d5"
],
hoverBackgroundColor: [
"#f38b4a",
"#56d798",
"#ff8397",
"#6970d5"
]
}]
},
options: {
scales: {
yAxes: [{
ticks:{
min : 0,
stepSize : 1,
fontColor : "#000",
fontSize : 14
},
gridLines:{
color: "#000",
lineWidth:2,
zeroLineColor :"#000",
zeroLineWidth : 2
},
stacked: true
}],
xAxes: [{
ticks:{
fontColor : "#000",
fontSize : 14
},
gridLines:{
color: "#fff",
lineWidth:2
}
}]
},
responsive:false,
chartArea: {
backgroundColor: 'rgba(251, 85, 85, 0.4)'
}
}
};
var ctx = document.getElementById("barChart").getContext("2d");
new Chart(ctx, config);
The canvas background is transparent by definition, like any element, so you just need to define the background-color in your canvas, for example, in your case you will need this CSS:
JSFiddle
canvas#barChart {
background-color: #f00;
}
or HTML inline, to clarify the idea:
<canvas id="barChart" width="600" height="300" style="background-color: #f00;"></canvas>
This works on latest chartjs
const custom_canvas_background_color = {
id: 'custom_canvas_background_color',
beforeDraw: (chart, args, options) => {
const {
ctx,
chartArea: { top, right, bottom, left, width, height },
scales: { x, y },
} = chart;
ctx.save();
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = '#E5E5E5';
ctx.fillRect(left, top, width, height);
ctx.restore();
},
};
Then add as plugin
plugins: [custom_canvas_background_color]
If you want to set a colour for the whole Canvas (and not just the plotting area), you can do it like this:
Chart.pluginService.register({
beforeDraw: ({ config: { options }, ctx }) => {
if (options.chartArea?.backgroundColor) {
ctx.save();
ctx.fillStyle = options.chartArea.backgroundColor;
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
}
}
});
const chart = new Chart(document.getElementById('chart'), {
options: {
chartArea: {
backgroundColor: 'rgba(255, 255, 255, 1)'
}
}
});
This will be applied to the PNG when using chart.toBase64Image()
You can achieve this by implementing this Chartjs plugin plugin / example. The plugin allows you to enhance your chart. For example zoom in or pan on to your chart. But also change the background color. Using setBackgroundColor(color); //updates the background color of the chart.

Categories