gradient background on radar chartjs - javascript

I've got a radar chartJs.
I cant figure out how to put inside the area a radial gradient.
When putting the current code, it only takes 1 color as background-color by default
current code:
let ctx = document.getElementById('chart-0').getContext("2d");
let gradient = ctx.createLinearGradient(0.000, 150.000, 300.000, 150.000);
// Add colors
gradient.addColorStop(0.035, 'rgba(234, 25, 78, 1.000)');
gradient.addColorStop(0.225, 'rgba(0, 8, 249, 1.000)');
gradient.addColorStop(0.983, 'rgba(42, 255, 0, 1.000)');
let data = {
backgroundColor: gradient,
labels: labelData,
datasets: [{
borderColor: presets.red,
data: [20,20,20,20,20],
label: labeldata
}]
};
const options = {
maintainAspectRatio: true,
spanGaps: false,
scale: {
pointLabels: {
fontSize: 14
}
},
elements: {
line: {
tension: 0.000001
}
},
legend: {
labels: {
fontSize: 16
}
}
};
chart = new Chart('chart-0', {
type: 'radar',
data: data,
options: options
});

Each dataset also should include backgroundColor property with assigned gradient values. I've created JSFiddle based on your code.

Related

Hover text of canvas in other div

I want to put text beside the canvas doughnut. This text is based on the hover information of each slide, but instead of appear on the top pf the image i want it to be next to it. (2 images as example)
https://jsfiddle.net/jak2e4zr/
HTML
<canvas id="myChart" ></canvas>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
JS
var ctx = document.getElementById("myChart");
var data = {
labels: ['Residential', 'Non-Residential', 'Utility'],
datasets: [
{
data: [19, 26, 55],
weight: 2,
spacing : 5,
borderWidth : 0,
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
circumference: 180,
rotation: -180,
plugins: {
legend: {
display: false
},
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0)',
borderColor: 'rgba(0, 0, 0, 0)',
displayColors: false,
titleAlign: 'center',
xAling: 'center'
}
},
hoverOffset: 15,
}
}); `
Image 1
Image 2
THANKS
The chart.js tooltip object accepts an additional property called position which, well, affects the position of the tooltip. By default it only accepts two strings for setting the mode being either "average" or "nearest". Luckily you're able to define your own mode by extending the Chart.Tooltip.positioners object.
As you want your tooltip to be somewhere in the middle, we can make something like this:
Chart.Tooltip.positioners.middle = function(elements, eventPosition) {
const chart = this._chart;
return {
x: chart.chartArea.width/2,
y: chart.chartArea.height/2
};
}
...so simply querying the chart's current dimensions and take the half of it. This mode can then be used by it's name "middle".
Here's a complete example:
var ctx = document.getElementById("myChart");
Chart.Tooltip.positioners.middle = function(elements, eventPosition) {
const chart = this._chart;
return {
x: chart.chartArea.width / 2,
y: chart.chartArea.height / 2
};
}
var data = {
labels: ['Residential', 'Non-Residential', 'Utility'],
datasets: [{
data: [19, 26, 55],
weight: 2,
spacing: 5,
borderWidth: 0,
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
responsive: false,
circumference: 180,
rotation: -180,
plugins: {
legend: {
display: false
},
tooltip: {
position: 'middle',
backgroundColor: '#ff0000',
titleColor: '#000000',
displayColors: false,
titleAlign: 'center',
xAlign: 'left'
}
},
hoverOffset: 15,
}
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>

Create space between legend and chart in charts.js [duplicate]

This question already has answers here:
Chart.js - Increase spacing between legend and chart
(13 answers)
Closed 1 year ago.
I am working with charts.js but I'm facing an issue. My legend and bar chart value overlaps a bit.
I am not able to resolve this issue, It would be appreciated if there is a solution to this issue
I have shared JS fiddle link below
https://jsfiddle.net/qh0yzmjf/1/
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: "top"
},
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);
}
}
});
}
}
}
});
I have also shared my code above
I don't know how to create space between legend and chart, and help will be appreciated thanks
If I am not wrong, there isnt a configuration built by chart js to put padding between the labels and the chart,although, the padding to the labels are applied in wor format, this means that chart js applies padding between labels, on the other hand, you can apply padding between the title of the chart and the labels.
If you want padding between the tittle of the chart and the chart you can use the following code:
plugins: {
title: {
display: true,
text:'Historico Mensual',
},
legend: {
labels: {
padding: 100
}
}
},
Another solution it could be to change the position of the labels to the bottom with the following code:
options: {
legend: {
display: true,
position: "bottom"
},
And adding a layput padding so the values dont get outside the canvas.
options: {
layout:{
padding:20
}
},

How to apply to different bground color for each area in Chart.js

In react-chartjs-2
In Line chart every grid should have different background colors.
Is this achievable with this library?
This is how LineChart should looks:
This is my Code/configuration:
const options = {
responsive: true,
scales: {
y: {
grid: {
backgroundColor: [
'rgba(36, 206, 0, 0.8)',
'rgba(255, 255, 0, .8)',
'rgba(255, 162, 0, 0.8)',
'rgba(36, 206, 0, 0.8)',
],
},
};
Thanks for reading.
You can use an inline plugin to achieve it:
var GradientBgPlugin = {
beforeDraw: function(chart, args, options) {
const ctx = chart.ctx;
const canvas = chart.canvas;
const chartArea = chart.chartArea;
// Chart background
var gradientBack = canvas.getContext("2d").createLinearGradient(0, 250, 0, 0);
gradientBack.addColorStop(0, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.16, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.17, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.25, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.26, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.5, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.51, "rgba(251,221,221,1)");
gradientBack.addColorStop(1, "rgba(251,221,221,1)");
ctx.fillStyle = gradientBack;
ctx.fillRect(chartArea.left, chartArea.bottom,
chartArea.right - chartArea.left, chartArea.top - chartArea.bottom);
}
};
Than just include it in your Chart options:
plugins: [GradientBgPlugin]
The result should be similar to this JSFiddle.
EDIT
For Reach Charts JS 2, you need small changes in setup. You define plugin this way:
const plugins = [{
beforeDraw: function(chart) {
const ctx = chart.ctx;
const canvas = chart.canvas;
const chartArea = chart.chartArea;
// Chart background
var gradientBack = canvas.getContext("2d").createLinearGradient(0, 250, 0, 0);
gradientBack.addColorStop(0, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.16, "rgba(213,235,248,1)");
gradientBack.addColorStop(0.17, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.25, "rgba(226,245,234,1)");
gradientBack.addColorStop(0.26, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.5, "rgba(252,244,219,1)");
gradientBack.addColorStop(0.51, "rgba(251,221,221,1)");
gradientBack.addColorStop(1, "rgba(251,221,221,1)");
ctx.fillStyle = gradientBack;
ctx.fillRect(chartArea.left, chartArea.bottom,
chartArea.right - chartArea.left, chartArea.top - chartArea.bottom);
}
}];
Than you plug it this way:
<Line data={data} plugins={plugins} />
You can see it working fine on CodeSandbox here.
You can write a custom inline plugin, that draws the colors on the chart Area. In the options section you can put an object with all the sections you want, from where to where and which color they need to be
Example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [100, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
plugins: {
backgrounds: {
hbars: [{
from: 28,
to: 100,
color: "rgb(195, 230, 195)"
},
{
from: 20,
to: 28,
color: "rgb(230, 220, 195)"
},
{
from: 0,
to: 20,
color: "rgb(230, 195, 195)"
}
]
}
}
},
plugins: [{
id: 'backgrounds',
beforeDraw: (chart, args, options) => {
const {
ctx,
chartArea,
scales: {
y
}
} = chart;
options.hbars.forEach((hBar) => {
ctx.save();
ctx.fillStyle = hBar.color;
ctx.fillRect(chartArea.left, y.getPixelForValue(hBar.from), chartArea.right - chartArea.left, y.getPixelForValue(hBar.to) - y.getPixelForValue(hBar.from));
ctx.restore();
})
}
}]
}
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.2.0/chart.js"></script>
</body>
Detailed explanation can be found here: https://medium.com/#omi10859/alternative-background-lines-in-chartjs-a626ce4d3bcb
We can use annotaion plugin with chartjs to create custom elements.
we can use annotation plugin to do this
import annotationPlugin from "chartjs-plugin-annotation";
import {Chart} from 'chart.js';
Chart.register(annotationPlugin);
this code will add a box to our chart
{
type: 'box', #type of draw
drawTime: 'beforeDraw', #this will decide background or foreground
yMin: 5, #value min on y axis
yMax: 10, #value max on y axis
borderColor: 'rgb(242, 244, 248, 0.9)', #border color of the box
borderWidth: 1, #boarder width for box
backgroundColor: '#F2F4F8', #colour of the box
}
# add option while rendering
const options = {
plugins: {annotation: {annotations: background_annotation}
}
this code render this

Char.js Interpolation linear

i'm trying to draw functions with Chart.js
I have a problem with my draw let's see :
here
This is the 'x' function and the line isn't straight
I don't know if it's a problem of resolution or of interpolation
So here is my chart :
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
borderWidth:2,
pointRadius :0,
borderColor: 'rgba(0, 0, 255, 1)',
label: 'Scatter Dataset',
data: JSON.parse(data),
fill: false,
lineTension: 0,
cubicInterpolationMode: 'linear'
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
},
pan: {
enabled: true,
mode: 'xy'
},
zoom: {
enabled: true,
mode: 'xy',
},
responsive: true,
maintainAspectRatio: true,
}
});
Thx guys
The problem is how chart.js is drawing the small line segments between data points. Here is a fiddle that animates a full opacity line over top of a lighter line. The second line is growing at a step=1 while the lighter line is nice and straight [{x:-100,y:-100},{x:100,y:100}]. If you change to step=10 you will see the line fill in straight.
In the code below (or in the fiddle) you can play around with changing the borderWidth, borderColor, and opacity. I tried adding borderCapStyle: 'round' and borderJoinStyle: 'round', but neither seemed to have much effect.
var ctx = document.getElementById("test").getContext("2d");
var i = -100;
var data = [{x: i, y: i}];
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
borderWidth: 2,
pointRadius: 0,
borderColor: 'rgba(0, 0, 255, 1)',
label: 'Scatter Dataset 1',
data: data,
fill: false,
lineTension: 0,
cubicInterpolationMode: 'linear'
}, {
borderWidth: 2,
pointRadius: 0,
borderColor: 'rgba(0, 0, 255, 0.4)',
label: 'Scatter Dataset 2',
data: [{x:-100,y:-100},{x:100,y:100}],
fill: false,
lineTension: 0,
cubicInterpolationMode: 'linear'
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
},
pan: {
enabled: true,
mode: 'xy'
},
zoom: {
enabled: true,
mode: 'xy',
},
responsive: true,
maintainAspectRatio: true,
}
});
var step = 1;
var intervalId = setInterval(function() {
i += step;
if (i <= 100) {
scatterChart.data.datasets[0].data.push({x:i,y:i});
scatterChart.update();
} else {
clearInterval(intervalId);
}
}, 200);
and
<canvas id="test" width="400" height="300"></canvas>

Hide points in ChartJS LineGraph

Originally I set the fill color for each point to be completely transparent. If I run my mouse over the graph, the points pop up. I want to hide all points so that the line graph is smooth.
You can achieve this by setting point's radius property in configuration options as follows:
var chartConfig = {
type: 'line',
options: {
elements: {
point:{
radius: 0
}
}
}
}
Tooltips for the points will also gone off.
You can set the pointRadius to zero.
var myChart = new Chart(
ctx, {
type: 'line',
data: {
labels: [...]
datasets: [
{
data: [...],
pointRadius: 0, # <<< Here.
}
]
},
options: {}
})
I had the same problem, but I wanted to keep the hover option active.
There is my solution:
const config = {
type: 'line',
data: {
datasets:[{
label: 'Température',
borderColor: 'rgb(255, 99, 132)',
data: tempE,
pointStyle: 'rect',
}]
},
options: {
elements:{
point:{
borderWidth: 0,
radius: 10,
backgroundColor: 'rgba(0,0,0,0)'
}
}
}
};

Categories

Resources