Chartjs Line Color Between Two Points - javascript

Is there any way to set line color of specific sections in between two points in chart.js?
I would like to color the section 00-07 gray, 07-15 red, and 15-23 blue.
Here is what I am passing as the data attribute in the options object to initialize the chart:
var chartData = {
labels: [/* a single dimensional array of strings */],
datasets: [
{
label: '',
data: [/* a single dimensional array of totals */],
fill: false,
backgroundColor: '#e7eaeb',
borderColor: red
}
]
};
I think this is where I need to add the graph section points and colors, but I do not know how.

HI Michael Hurley I think you should use:
interpolation:
https://www.chartjs.org/docs/latest/samples/line/interpolation.html
or
Multi-axis: https://www.chartjs.org/docs/latest/samples/line/multi-axis.html
My idea is we have 3 datasets with multi-color,
End of dataset1 is first of dataset2.
Here my Example:
window.chartColors = { red: 'rgb(255, 99, 132)', orange: 'rgb(255, 159, 64)', yellow: 'rgb(255, 205, 86)', green: 'rgb(75, 192, 192)', blue: 'rgb(54, 162, 235)', purple: 'rgb(153, 102, 255)', grey: 'rgb(201, 203, 207)' };
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var config = {
type: 'line',
data: {
labels: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
datasets: [{
label: 'Cubic interpolation (monotone)',
data: [0, 20, 20, 60, 60, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN],
borderColor: window.chartColors.red,
backgroundColor: 'rgba(0, 0, 0, 0)',
fill: false,
cubicInterpolationMode: 'monotone'
}, {
label: 'Cubic interpolation (default)',
data: [NaN, NaN, NaN, NaN, 60, 120, 140, 180, 120, NaN, NaN, NaN, NaN],
borderColor: window.chartColors.blue,
backgroundColor: 'rgba(0, 0, 0, 0)',
fill: false,
}, {
label: 'Linear interpolation',
data: [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 120, 125, 105, 110, 170],
borderColor: window.chartColors.green,
backgroundColor: 'rgba(0, 0, 0, 0)',
fill: false,
lineTension: 0
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart - Cubic interpolation mode'
},
tooltips: {
mode: 'index'
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
},
ticks: {
suggestedMin: -10,
suggestedMax: 200,
}
}]
}
}
};
var ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:75%;">
<canvas id="canvas"></canvas>
</div>

Latest versions of ChartJS allow you to customize line segments individually, which can be used to change the color and also the style (dashed etc) of a specific segment.
const config = {
type: 'line',
data: {
labels: Utils.months({count: 7}),
datasets: [{
label: 'My First Dataset',
data: [65, 59, NaN, 48, 56, 57, 40],
borderColor: 'rgb(75, 192, 192)',
segment: {
borderColor: ctx => skipped(ctx, 'rgb(0,0,0,0.2)') || down(ctx, 'rgb(192,75,75)'),
borderDash: ctx => skipped(ctx, [6, 6]),
}
}]
},
options: genericOptions
};
See https://www.chartjs.org/docs/master/samples/line/segments.html for more info.

The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterLayout hook to create a linear gradient through CanvasRenderingContext2D.createLinearGradient().
In the following example, the linear gradient is created from the colors defined in data.dataset.colors.
new Chart('myChart', {
type: 'line',
plugins: [{
afterLayout: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var gradientStroke = ctx.createLinearGradient(xAxis.left, 0, xAxis.right, 0);
var dataset = chart.data.datasets[0];
dataset.colors.forEach((c, i) => {
var stop = 1 / (dataset.colors.length - 1) * i;
gradientStroke.addColorStop(stop, dataset.colors[i]);
});
dataset.backgroundColor = gradientStroke;
dataset.borderColor = gradientStroke;
dataset.pointBorderColor = gradientStroke;
dataset.pointBackgroundColor = gradientStroke;
dataset.pointHoverBorderColor = gradientStroke;
dataset.pointHoverBackgroundColor = gradientStroke;
}
}],
data: {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
datasets: [{
label: 'My Dataset',
data: [101, 122, 103, 115, 95, 94, 100, 108, 112, 115, 119, 120, 109, 108, 105, 116, 117, 108, 109, 114],
fill: false,
colors: ['gray', 'gray', 'gray', 'gray','gray', 'gray', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue']
}]
},
options: {
scales: {
yAxes: [{
ticks: {
min: 0
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="70"></canvas>

In V3 you can make use of the segment option in the dataset to style specific line parts:
new Chart('myChart', {
type: 'line',
data: {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
datasets: [{
label: 'My Dataset',
data: [101, 122, 103, 115, 95, 94, 100, 108, 112, 115, 119, 120, 109, 108, 105, 116, 117, 108, 109, 114],
segment: {
borderColor: (ctx) => {
const xVal = ctx.p1.parsed.x;
if (xVal <= 7) {
return 'gray';
} else if (xVal <= 15) {
return 'red'
} else {
return 'blue'
}
},
},
}]
},
options: {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
<canvas id="myChart" height="70"></canvas>

I've been wanting to let everyone know a way for react chart.
import React from "react";
import { LineController } from 'chart.js';
import Chart from 'chart.js/auto';
class MultiLineController extends LineController {
draw() {
const ctx = this.chart.ctx;
const meta = this.getMeta();
const points = meta.data || [];
const colors = this.getDataset().colors || [];
const area = this.chart.chartArea;
colors.forEach((color, idx) => {
meta.dataset.options.borderColor = color;
meta.dataset.draw(ctx, area, idx, 2);
});
meta.dataset.draw(ctx, area, colors.length, points.length - colors.length);
}
}
MultiLineController.id = "multicolorLine";
MultiLineController.defaults = LineController.defaults;
Chart.register(MultiLineController);
export default function App() {
React.useEffect(() => {
const ctx = document.getElementById("line-chart").getContext("2d");
window.lineChart = new Chart(ctx, {
type: 'multicolorLine',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
colors: ['red', 'green', 'blue', 'yellow']
}]
},
options: {}
});
return () => window.lineChart.destroy();
}, []);
return (
<div style={{width: '100%', height: 300}}>
<canvas id="line-chart" />
</div>
);
}
Here is screenshot of this chart.
React Chart Component implemented by chart.js

Related

ChartJS Email HTTP Request API

Given my chartJS config below
var ctx = document.getElementById('myChart').getContext('2d');
Chart.defaults.global.defaultFontColor = 'rgba(255, 255, 255, 1)';
Chart.defaults.global.defaultFontFamily = 'Arial';
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Investment', 'Sustainable'],
datasets: [{
label: 'myLabel',
data: [11, 5],
backgroundColor: [
'rgba(234, 82, 4, 0.2)',
'rgba(0, 121, 109, 0.2)'
],
borderColor: [
'rgba(234, 82, 4, 1)',
'rgba(0, 121, 109, 1)'
],
borderWidth: 1
}]
},
options: {
legend: {
labels: {
display: true
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
},
gridLines: {
color: 'rgba(255, 255, 255, 0.1)'
},
scaleLabel: {
display: true,
},
}],
}
}
});
I need to get something as close as the following
Using Quickchart API, I am submitting the config through the URL, but I am having trouble setting the labels color? options:{legend:{labels:{fontColor: 'white'}},
https://quickchart.io/chart?c={type:%27bar%27,data:{labels:[%27Investment%27,%27Sustainable%20%27],datasets:[{label:%27myLabel%27,data:[11,5],backgroundColor:%20[%27rgba(234,%2082,%204,%200.2)%27,%27rgba(0,%20121,%20109,%200.2)%27],borderColor:%20[%27rgba(234,%2082,%204,%201)%27,%27rgba(0,%20121,%20109,%201)%27]}]}}
Gives me
Update 2
I am trying to construct the URL but I am getting some issues;
<script type="text/javascript">// <![CDATA[
var carbon = {
type: 'bar',
data: {
labels: ['Average Investment', 'Sustainable Investment'],
datasets: [{
label: 'Tonnes of CO2 per year',
data: [11, 5],
borderWidth: 1,
backgroundColor: ['rgba(234, 82, 4, 0.2)', 'rgba(0, 121, 109, 0.2)'],
borderColor: ['rgba(234, 82, 4, 1)', 'rgba(0, 121, 109, 1)'],
}]
},
options: {
plugins: {
datalabels: {
anchor: 'end',
align: 'top',
color: '#fff',
backgroundColor: 'rgba(34, 139, 34, 0.6)',
borderColor: 'rgba(34, 139, 34, 1.0)',
borderWidth: 1,
borderRadius: 5,
formatter: (value) => {
return value + 'k';
},
},
},
legend: {
labels: {
fontColor: 'white'
}
},
title: {
display: true,
text: 'Tones of CO2 pear year'
},
scales: {
xAxes: [{
ticks: {
fontColor: 'white'
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
fontColor: 'white'
},
gridLines: {
color: 'rgba(255, 255, 255, 0.1)'
},
}]
}
}
};
var link = JSON.stringify(carbon);
var link0 = JSON.parse(link);
var link2 = encodeURI(link0);
console.log(typeof link0+ " "+typeof link+" ------------------ "+typeof link2);
// ]]></script>
<div><img width="200" height="100" src="https://quickchart.io/chart?c="/></div>
Which should render the following
Which version of Chart.js are you using because it seems to be working fine with your config.
quickChart: https://quickchart.io/chart?bkg=%23002A5E&c={%20type:%20%27bar%27,%20data:%20{%20labels:%20[%27Investment%27,%20%27Sustainable%27],%20datasets:%20[%20{%20label:%20%27Tonnes%20of%20CO2%20per%20year%27,%20data:%20[11,%205],%20borderWidth:%201,%20backgroundColor:%20[%20%27rgba(234,%2082,%204,%200.2)%27,%20%27rgba(0,%20121,%20109,%200.2)%27%20],%20borderColor:%20[%20%27rgba(234,%2082,%204,%201)%27,%20%27rgba(0,%20121,%20109,%201)%27%20],%20}%20]%20},%20options:%20{%20legend:%20{labels:%20{fontColor:%20%27white%27}},%20scales:%20{%20xAxes:%20[{ticks:%20{fontColor:%20%27white%27}}],%20yAxes:%20[{%20ticks:%20{%20beginAtZero:%20true,%20fontColor:%20%27white%27%20},%20gridLines:%20{%20color:%20%27rgba(255,%20255,%20255,%200.1)%27%20},%20}]%20}%20}%20}
var options = {
type: 'bar',
data: {
labels: ['Investment', 'Sustainable'],
datasets: [{
label: 'Tonnes of CO2 per year',
data: [11, 5],
borderWidth: 1,
backgroundColor: [
'rgba(234, 82, 4, 0.2)',
'rgba(0, 121, 109, 0.2)'
],
borderColor: [
'rgba(234, 82, 4, 1)',
'rgba(0, 121, 109, 1)'
],
}]
},
options: {
legend: {
labels: {
fontColor: 'white'
}
},
scales: {
xAxes: [{
ticks: {
fontColor: 'white'
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
fontColor: 'white'
},
gridLines: {
color: 'rgba(255, 255, 255, 0.1)'
},
}]
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
canvas {
background-color: #002A5E;
}
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>

Multiple Range Highlighting of Background in Chart.js

From this question I'm looking to turn into a multiple range highlight
But there 1 annoying bug I didn't succeed to solve
background is superposing, if you uncheck a dataset on the top, background alpha change
Here my work so far: https://jsfiddle.net/742zut83/588/
Why the custom draw function executed for each dataset? Once highlights done originalLineDraw is returned
draw : function() {
var chart = this.chart;
// Get the object that determines the region to highlight.
var yHighlightRanges = chart.config.data.yHighlightRanges;
let ctx = chart.chart.ctx;
yHighlightRanges.forEach(function(Range) {
var yRangeBegin = Range.begin;
var yRangeEnd = Range.end;
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-0'];
var yRangeBeginPixel = yaxis.getPixelForValue(yRangeBegin);
var yRangeEndPixel = yaxis.getPixelForValue(yRangeEnd);
ctx.save();
// The fill style of the rectangle we are about to fill.
ctx.fillStyle = Range.rgb;
// Fill the rectangle that represents the highlight region. The parameters are the closest-to-starting-point pixel's x-coordinate,
// the closest-to-starting-point pixel's y-coordinate, the width of the rectangle in pixels, and the height of the rectangle in pixels, respectively.
ctx.fillRect(xaxis.left, Math.min(yRangeBeginPixel, yRangeEndPixel), xaxis.right - xaxis.left, Math.max(yRangeBeginPixel, yRangeEndPixel) - Math.min(yRangeBeginPixel, yRangeEndPixel));
ctx.restore();
});
// Apply the original draw function for the line chart.
originalLineDraw.apply(this, arguments);
}
var ctx = document.getElementById("myChart");
// The original draw function for the line chart. This will be applied after we have drawn our highlight range (as a rectangle behind the line chart).
var originalLineDraw = Chart.controllers.line.prototype.draw;
// Extend the line chart, in order to override the draw function.
Chart.helpers.extend(Chart.controllers.line.prototype, {
draw : function() {
var chart = this.chart;
// Get the object that determines the region to highlight.
var yHighlightRanges = chart.config.data.yHighlightRanges;
let ctx = chart.chart.ctx;
yHighlightRanges.forEach(function(Range) {
var yRangeBegin = Range.begin;
var yRangeEnd = Range.end;
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-0'];
var yRangeBeginPixel = yaxis.getPixelForValue(yRangeBegin);
var yRangeEndPixel = yaxis.getPixelForValue(yRangeEnd);
ctx.save();
// The fill style of the rectangle we are about to fill.
ctx.fillStyle = Range.rgb;
// Fill the rectangle that represents the highlight region. The parameters are the closest-to-starting-point pixel's x-coordinate,
// the closest-to-starting-point pixel's y-coordinate, the width of the rectangle in pixels, and the height of the rectangle in pixels, respectively.
ctx.fillRect(xaxis.left, Math.min(yRangeBeginPixel, yRangeEndPixel), xaxis.right - xaxis.left, Math.max(yRangeBeginPixel, yRangeEndPixel) - Math.min(yRangeBeginPixel, yRangeEndPixel));
ctx.restore();
});
// Apply the original draw function for the line chart.
originalLineDraw.apply(this, arguments);
}
});
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: 'Season 1',
data: [12, 17, 3, 5, 9, 3],
fill: false,
borderColor: 'rgba(0, 200, 0, 1)'
},
{
label: 'Season 2',
data: [5, 14, 3, 15, 9, 13],
fill: false,
borderColor: 'rgba(200, 0, 0, 1)'
}
],
// This, if it exists at all, defines the highlight region.
yHighlightRanges : [
{
begin: 0,
end: 6,
rgb: 'rgba(100, 100, 100, 0.2)'
},
{
begin: 6,
end: 12,
rgb: 'rgba(200, 100, 200, 0.2)'
},
{
begin: 12,
end: 18,
rgb: 'rgba(0, 100, 200, 0.2)'
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Why not using simply the annotation plugin?
Here is your example with annotation plugin, using Box annotations:
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: 'Season 1',
data: [12, 17, 3, 5, 9, 3],
fill: false,
borderColor: 'rgba(0, 200, 0, 1)'
},
{
label: 'Season 2',
data: [5, 14, 3, 15, 9, 13],
fill: false,
borderColor: 'rgba(200, 0, 0, 1)'
}
]
},
options: {
scales: {
yAxes: [{
id: 'y-axis-1',
ticks: {
beginAtZero:true
}
}]
},
annotation: {
drawTime: "afterDraw",
annotations: [{
id: 'box1',
type: 'box',
yScaleID: 'y-axis-1',
yMin: 0,
yMax: 6,
backgroundColor: 'rgba(100, 100, 100, 0.2)',
borderColor: 'rgba(100, 100, 100, 0.2)',
},{
id: 'box2',
type: 'box',
yScaleID: 'y-axis-1',
yMin: 6,
yMax: 12,
backgroundColor: 'rgba(200, 100, 200, 0.2)',
borderColor: 'rgba(200, 100, 200, 0.2)',
},{
id: 'box3',
type: 'box',
yScaleID: 'y-axis-1',
yMin: 12,
yMax: 18,
backgroundColor: 'rgba(0, 100, 200, 0.2)',
borderColor: 'rgba(0, 100, 200, 0.2)',
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
And this is your fiddle updated: https://jsfiddle.net/beaver71/50L21shp/

Chart JS — Conditional horizontal row background colours

I'm a bit stuck on adding conditional background colours to a row in ChartJS, based on numbers on the vertical axis.
Eg.
If the vertical axis is between 0 - 6, background colour for those rows is green.
If the vertical axis is between 6 - 12 background colour for those rows is grey
If the vertical axis is > 12 background colour for those rows is red
Has anyone done something like this before?
I've attached a picture that roughly describes the functionality.
Cheers!
There is no option to do this with chartjs. However you can write your own plugin and draw the background by yourself in the beforeDraw hook for example.
var chart = new Chart(ctx, {
plugins: [{
beforeDraw: function(chart) {
//..
}
}]
});
You can get all the information to calculate the height of an y-axis-segment from the chart parameter.
I've included a snippet below how this could be implemented. Note however that this is more a proof of concept than a proper implementation:
var canvas = document.getElementById('myChart');
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(51, 204, 51)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var myLineChart = new Chart(canvas,
{
type: 'line',
data: {
labels: ['1', '2', '3', '4', '5'],
datasets: [
{
label: '# of Votes',
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [2, 5, 12.5, 9, 6.3]
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Conditional Background'
},
backgroundRules: [{
backgroundColor: window.chartColors.green,
yAxisSegement: 6
}, {
backgroundColor: window.chartColors.grey,
yAxisSegement: 12
}, {
backgroundColor: window.chartColors.red,
yAxisSegement: Infinity
}],
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
},
plugins: [{
beforeDraw: function (chart) {
var ctx = chart.chart.ctx;
var ruleIndex = 0;
var rules = chart.chart.options.backgroundRules;
var yaxis = chart.chart.scales["y-axis-0"];
var xaxis = chart.chart.scales["x-axis-0"];
var partPercentage = 1 / (yaxis.ticksAsNumbers.length - 1);
for (var i = yaxis.ticksAsNumbers.length - 1; i > 0; i--) {
if (yaxis.ticksAsNumbers[i] < rules[ruleIndex].yAxisSegement) {
ctx.fillStyle = rules[ruleIndex].backgroundColor;
ctx.fillRect(xaxis.left, yaxis.top + ((i - 1) * (yaxis.height * partPercentage)), xaxis.width, yaxis.height * partPercentage);
} else {
ruleIndex++;
i++;
}
}
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>
Shiffty's answer is right on point, however it only works if the background values are present on the yAxis, which is not always the case... depends on what fits. A more generic solution is to calculate the actual values:
var canvas = document.getElementById('myChart');
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(51, 204, 51)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var myLineChart = new Chart(canvas,
{
type: 'line',
data: {
labels: ['1', '2', '3', '4', '5'],
datasets: [
{
label: '# of Votes',
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [2, 5, 12.5, 9, 6.3]
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Conditional Background'
},
backgroundRules: [{
backgroundColor: window.chartColors.green,
yAxisSegement: 6
}, {
backgroundColor: window.chartColors.grey,
yAxisSegement: 12
}, {
backgroundColor: window.chartColors.red,
yAxisSegement: 999999
}],
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
},
plugins: [{
beforeDraw: function (chart) {
var rules = chart.chart.options.backgroundRules;
var ctx = chart.chart.ctx;
var yAxis = chart.chart.scales["y-axis-0"];
var xaxis = chart.chart.scales["x-axis-0"];
for (var i = 0; i < rules.length; ++i) {
var yAxisSegement = (rules[i].yAxisSegement > yAxis.ticksAsNumbers[0] ? yAxis.ticksAsNumbers[0] : rules[i].yAxisSegement);
var yAxisPosStart = yAxis.height - ((yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]) + chart.chart.controller.chartArea.top;
var yAxisPosEnd = (i === 0 ? yAxis.height : yAxis.height - ((rules[i - 1].yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]));
ctx.fillStyle = rules[i].backgroundColor;
ctx.fillRect(xaxis.left, yAxisPosStart, xaxis.width, yAxisPosEnd - yAxisPosStart + chart.chart.controller.chartArea.top);
}
}
}]
});

Chartjs doughnut chart with gradient color

I created a doughnut chart. Is there any chance to make that colors like gradient ? I saw this post, I tried to implement on my own chart but I could not.
Any help, I will be grateful.
var ctx = $('#teamDoughnutChart');
var doughnutBar = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["A", "B", "C", "D", "E"],
datasets: [{
label: "Status",
backgroundColor: [
'rgba(192, 57, 43,1)',
'rgba(244, 187, 18, 1)',
'rgba(41, 128, 185,1)',
'rgba(39, 174, 96,1)',
'rgba(191, 199, 215, 1)'
],
borderColor: 'rgba(73, 79, 92, 0)',
data: [24, 38, 96, 79, 41]
}]
},
options: {
cutoutPercentage: 70,
maintainAspectRatio: false,
startAngle: 0,
tooltips: {
mode: 'index',
backgroundColor: '#393e48'
},
legend: {
position: 'bottom',
labels: {
fontSize: 12,
padding: 25,
boxWidth: 15
}
}
}
});
<canvas id="teamDoughnutChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a same problem. I found solution. Try this
var canvas = $('#teamDoughnutChart');
var ctx = canvas.getContext('2d');
var gradientColors = [
{
start: '#f3bb98',
end: '#ea8ba9'
},
{
start: '#F6A064',
end: '#ED5384'
}
];
var gradients = [];
gradientColors.forEach( function( item ){
var gradient = ctx.createLinearGradient(0, 0, 150 , 150);
gradient.addColorStop(0, item.start);
gradient.addColorStop(1, item.end);
gradients.push(gradient);
});
var doughnutBar = new Chart(canvas, {
type: 'doughnut',
data: {
labels: ["A", "B"],
datasets: [{
label: "Status",
backgroundColor: gradients,
borderColor: 'rgba(73, 79, 92, 0)',
data: [24, 38]
}]
},
options: {
cutoutPercentage: 70,
maintainAspectRatio: false,
startAngle: 0,
tooltips: {
mode: 'index',
backgroundColor: '#393e48'
},
legend: {
position: 'bottom',
labels: {
fontSize: 12,
padding: 25,
boxWidth: 15
}
}
}
});

chartjs show dot point on hover over line chart

I am using Chartjs v.1.0.2 and trying to set a point dot only to appear on hover over chart. After it it should be removed. I have managed to show it, by changing the object value, but it is not fluid motion and it doesn't show point always. This also doesn't hide it on hover out.
How can it be fluid and hide when mouse is not over?
window.onload = function(){
var ctx = $("#chart1").get(0).getContext("2d");
var chart1 = new Chart(ctx).Line(data1, options);
$("#chart1").hover(function(e) {
var activeBars = chart1.getPointsAtEvent(e);
activeBars[0].display = true;
// console.log(activeBars[0]);
chart1.update();
});
};
var data1 = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(95,186,88,0.7)",
strokeColor: "rgba(95,186,88,1)",
pointColor: "rgba(95,186,88,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
var options = {
responsive: true,
bezierCurve : false,
scaleShowLabels: false,
scaleFontSize: 0,
pointDot : false,
scaleBeginAtZero: true,
scaleShowHorizontalLines: false,
scaleShowVerticalLines: true,
scaleGridLineColor : "rgba(232,232,232)",
showTooltips: true,
customTooltips: function (tooltip) {
var tooltipEl = $('#chartjs-tooltip');
if (!tooltip) {
tooltipEl.css({
opacity: 0
});
return;
}
tooltipEl.removeClass('above below');
tooltipEl.addClass(tooltip.yAlign);
// split out the label and value and make your own tooltip here
var parts = tooltip.text.split(":");
var innerHtml = '<span>' + parts[0].trim() + '</span> : <span><b>' + parts[1].trim() + '</b></span>';
tooltipEl.html(innerHtml);
tooltipEl.css({
opacity: 1,
left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
fontFamily: tooltip.fontFamily,
fontSize: tooltip.fontSize,
fontStyle: tooltip.fontStyle,
});
}
};
simplified fiddle
Tested with Chart.js v2.6.0
Global setting will do the trick:
Chart.defaults.global.hover.intersect = false;
Or directly in chart config:
options: {
hover: {
intersect: false;
}
}
And point settings for dataset.
initial color of the point should be transparent
hover color must be set to the desired color
e.g.
datasets: [{
label: 'My First dataset',
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgb(255, 99, 132)',
data: [10, 30, 46, 2, 8, 50, 0],
fill: false,
pointBorderColor: 'rgba(0, 0, 0, 0)',
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: 'rgb(255, 99, 132)',
pointHoverBorderColor: 'rgb(255, 99, 132)'}],...
window.onload = function() {
const mode = 'index';
const intersect = false;
const config = {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgb(255, 99, 132)',
data: [10, 30, 46, 2, 8, 50, 0],
fill: false,
pointBorderColor: 'rgba(0, 0, 0, 0)',
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: 'rgb(255, 99, 132)',
pointHoverBorderColor: 'rgb(255, 99, 132)',
}, {
label: 'My Second dataset',
borderColor: 'rgb(54, 162, 235)',
backgroundColor: 'rgb(54, 162, 235)',
data: [7, 49, 46, 13, 25, 30, 22],
fill: false,
pointBorderColor: 'rgba(0, 0, 0, 0)',
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: 'rgb(54, 162, 235)',
pointHoverBorderColor: 'rgb(54, 162, 235)',
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Mode: index, intersect = false'
},
tooltips: {
mode: 'index',
intersect: intersect,
},
hover: {
mode: mode,
intersect: intersect
},
}
};
const ctx = document.getElementById('canvas').getContext('2d');
const chart = new Chart(ctx, config);
}
<canvas id="canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
Edit: The following solution is for Chart.js v1.0.2 (the latest version at the time this solution was proposed). Please refer to this answer which provides a solution for Chart.js v2.x.x.
I ran into a similar situation a while back and resolved this by making the default point dot "invisible" as follows:
setting pointDotRadius to 1
setting pointStrokeColor to white with the alpha set to 0
The two steps above make the default point dot very small, this, in combination with the transparent point stroke, makes the default point dot invisible. Now if we make the pointDotStrokeWidth large enough, we can achieve the desired hover effect. i.e.
set pointDotStrokeWidth to a larger value (I used 8)
set the desired values for pointColor, pointHighlightFill, pointHighlightStroke
[Note: the same effect can be achieved by making pointColor
transparent but if you are plotting multiple datasets, then the
tooltip wouldn't show the corresponding line color next to the data
value.]
Example below (or you can checkout this Fiddle: ChartJS - Show Points on Hover):
var data = {
labels: ["Point0", "Point1", "Point2", "Point3", "Point4"],
datasets: [
{
label: "My Chart",
fillColor: "rgba(87, 167, 134, 0.2)",
strokeColor: "rgba(87, 167, 134, 1)",
pointColor: "rgba(87, 167, 134, 1)",
pointStrokeColor: "rgba(255, 255, 255, 0)",
pointHighlightFill: "rgba(87, 167, 134, 0.7)",
pointHighlightStroke: "rgba(87, 167, 134, 1)",
data: [5, 39, 109, 19, 149]
}
]
};
var ctx = document.getElementById("my_chart").getContext("2d");
myChart = new Chart(ctx).Line(data, {
responsive : true,
bezierCurve: false,
datasetFill: true,
pointDotRadius: 1,
pointDotStrokeWidth: 8,
pointHitDetectionRadius: 20,
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<canvas id="my_chart"></canvas>
$("#chart1").mouseover(function(e) {
chart1.datasets[0].points[0].display = true;
chart1.update();
});
$("#chart1").mouseout(function(e) {
chart1.datasets[0].points[0].display = false;
chart1.update();
});
Try using mouseover and mouseout as shown below. Similarly you can also use mouseenter and mouseleave methods to handle events.
$("#chart1").mouseover(function(e) {
var activeBars = chart1.getPointsAtEvent(e);
activeBars[0].display = true;
chart1.update();
});
$("#chart1").mouseout(function(e) {
var activeBars = chart1.getPointsAtEvent(e);
activeBars[0].display = false;
chart1.update();
});
This is a six years old question but I think in 2022 we can use ChartJS version 4.0.1.
ChartJS supports interactions behavior, and they can be configured via interaction, hover or tooltips settings on the chart configuration.
For this we will use the hover setting and select the index mode. This mode finds an item at the same index. If the intersect setting is false the nearest item, in the x direction, is used to determine the index.
Here is a working snippet
const 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
}
]
}
const options = {
maintainAspectRatio: false,
elements: {
point: {
hoverRadius: 6,
},
},
hover: {
mode: 'index',
intersect: false,
},
}
const config = {
type: 'line',
data,
options,
}
const $chart = document.getElementById('chart')
const chart = new Chart($chart, config)
<div class="wrapper" style="width: 98vw; height: 180px">
<canvas id="chart"></canvas>
</div>
<script src="https://unpkg.com/chart.js#4.0.1/dist/chart.umd.js"></script>

Categories

Resources