Can the colors of bars in a bar chart be varied based on their value? - chart.js

Using chart.js 2, can the colors of the bars in a bar-cart be varied based on their value?
For example, if the scale is 0 - 100, columns with 50% and above could be green, while 0-49% could be red.

As far as I know there is no configuration or callback for each individual point being drawn. The best way I can think of to do this would be to create a function that would modify your chart config/data object. This isn't the most elegant way to deal with the problem, but it would work.
The Fix
Pass your chart config/data object to a function that will add the background color.
Main Point of the example is function AddBackgroundColors(chartConfig)
Example:
function AddBackgroundColors(chartConfig) {
var min = 1; // Min value
var max = 100; // Max value
var datasets;
var dataset;
var value;
var range = (max - min);
var percentage;
var backgroundColor;
// Make sure the data exists
if (chartConfig &&
chartConfig.data &&
chartConfig.data.datasets) {
// Loop through all the datasets
datasets = chartConfig.data.datasets;
for (var i = 0; i < datasets.length; i++) {
// Get the values percentage for the value range
dataset = datasets[i];
value = dataset.data[0];
percentage = value / range * 100;
// Change the background color for this dataset based on its percentage
if (percentage > 100) {
// > 100%
backgroundColor = '#0000ff';
} else if (percentage >= 50) {
// 50% - 100%
backgroundColor = '#00ff00';
} else {
// < 50%
backgroundColor = '#ff0000';
}
dataset.backgroundColor = backgroundColor;
}
}
// Return the chart config object with the new background colors
return chartConfig;
}
var chartConfig = {
type: 'bar',
data: {
labels: ["percentage"],
datasets: [{
label: '100%',
data: [100]
}, {
label: '50%',
data: [50]
}, {
label: '49%',
data: [49]
}, {
label: '5%',
data: [5]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
chartConfig = AddBackgroundColors(chartConfig);
var myChart = new Chart(ctx, chartConfig);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.2/Chart.bundle.min.js"></script>
<canvas id="canvas" width="400" height="200"></canvas>

In Chart.js 2 it is possible to set multiple colors with an array.
So you can define the backgroundColor as an array of color strings, matching the datasets data.
var myChart = new Chart(ctx, {
datasets: [{
label: 'Votes',
data: [1, 2, 3],
// Make the first bar red, the second one green and the last one blue
backgroundColor: ['#f00', '#0f0', '#00f']
}]
});
You can easily generate an array based on the values in data:
function getColorArray(data, threshold, colorLow, colorHigh) {
var colors = [];
for(var i = 0; i < data.length; i++) {
if(data[i] > threshold) {
colors.push(colorHigh);
} else {
colors.push(colorLow);
}
}
return colors;
}
See this fiddle for a working demo

Related

Is it possible to draw a bar and arrow/pointer on the right side of a chart?

I currently have this chart.
I'm attempting to create something like this.
The bar on the side is static, but the section "heights" need to be programmable when the page loads. I attempted encoding in an SVG but I wasn't able to get it to stick to the chart.
I've got no clue how to make the final (current value) node to appear as an arrow pointing to the bar (or alternatively, as just a horizontal bar across the vertical one).
I made a sample codepen to simulate the dynamic chart I currently have.
(Or, per StackOverflow's requirements, the JS code used: )
var randoms = [...Array(11)].map(e=>~~(Math.random()*11));
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: randoms,
datasets: [{
label: 'value',
data: randoms
}]
},
options: {
scales: {
y: {
grace: 10,
}
}
}
});
function populate(){
let temp = ~~(Math.random()*11);
myChart.data.datasets[0].data.shift();
myChart.data.datasets[0].data.push(temp);
myChart.update();
}
setInterval(populate, 10000);
Any general pointers are also appreciated - I'm very new to all of this.
You can write a custom plugin for this, I added padding on the right to give space for the arrow to be drawn. You can play with the multiplyer values to make the arrow bigger/smaller
Example:
var randoms = [...Array(11)].map(e => ~~(Math.random() * 11));
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: randoms,
datasets: [{
label: 'value',
data: randoms,
borderColor: 'red',
backgroundColor: 'red'
}]
},
options: {
layout: {
padding: {
right: 25
}
},
scales: {
y: {
grace: 10
}
}
},
plugins: [{
id: 'arrow',
afterDraw: (chart, args, opts) => {
const {
ctx
} = chart;
chart._metasets.forEach((meta) => {
let point = meta.data[meta.data.length - 1];
ctx.save();
ctx.fillStyle = point.options.backgroundColor;
ctx.moveTo(point.x, (point.y - point.y * 0.035));
ctx.lineTo(point.x, (point.y + point.y * 0.035));
ctx.lineTo((point.x + point.x * 0.025), point.y)
ctx.fill();
ctx.restore();
})
}
}]
});
function populate() {
let temp = ~~(Math.random() * 11);
myChart.data.datasets[0].data.shift();
myChart.data.datasets[0].data.push(temp);
myChart.update();
}
//setInterval(populate, 10000);
<script src="https://npmcdn.com/chart.js#latest/dist/chart.min.js"></script>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"></canvas>
</div>

Show highest value untop of a bars when dataset is stacked (chartjs)

I have this code:
animation: {
duration: 500,
onComplete: function() {
var ctx = this.chart.ctx;
var chart = this;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
var datasets = this.config.data.datasets;
ctx.font = "15px QuickSand";
datasets.forEach(function (dataset, i) {
switch ( chart.getDatasetMeta(i).type ) {
case "bar":
ctx.fillStyle = "#303030";
chart.getDatasetMeta(i).data.forEach(function (p, j)
{
ctx.fillText(datasets[i].data[j], p._model.x, p._model.y - 10);
});
break;
}
});
}
}
And these datasets:
datasets: [
{
backgroundColor: '#f87979',
data: [6500, 5500]},
{
backgroundColor: '#f8f8ee',
data: [4800, 5600]
}
]
The dataset is set to be stacked using.
scales: {
xAxes: [{
barThickness: 25,
stacked: true,
ticks: {
beginAtZero: true,
padding: 0,
fontSize: 13
}
}],
yAxes: [{
stacked: true,
display: false
}]
},
What the above code does is placing the values over the bars. My problem is that i want to show the highest value from each dataset at above each bar.
And not all the values from each point.
Can you guys help me with this? I have been trying to do this for like a 1 day now.
To clearify instead of this:
Image with all values
I want this:
Image with wanted values
check out this jsfiddle: https://jsfiddle.net/umsbywLg/2/
essentially I calculated the max value and then drew that on top on the stacked bars:
onComplete: function() {
var ctx = this.chart.ctx;
var chart = this;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
var datasets = this.config.data.datasets;
ctx.font = "15px QuickSand";
ctx.fillStyle = "#303030";
datasets.forEach(function (dataset, i) {
var maxValue = 0;
chart.getDatasetMeta(i).data.forEach(function (p, j) {
if(maxValue < datasets[j].data[i]) {
maxValue = datasets[j].data[i];
}
});
ctx.fillText(maxValue, datasets[i]._meta[0].data[i]._view.x, 20);
});
}

ChartJS line chart x = y not rendering astraight line

I need to render some line that has many points (200) and at the beginning x equals y.
But as you can see on this codepen, the line is not straight.
Is there a way to have a smooth rendering ?
Thank you very much
var ctx = document.getElementById("myChart");
function generateFakeData() {
var res = [];
var i = 0;
for (i = 0; i < 200; ++i) {
res.push(i);
}
return res;
}
var myChart = new Chart(ctx, {
type: "line",
data: {
labels: generateFakeData(),
datasets: [
{
label: "# of Votes",
data: generateFakeData(),
radius: 0,
borderColor: "#156FB4"
}
]
},
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
}
});
If you were to change your fake data function to be:
function generateFakeData() {
var res = [];
res[0] = 0;
res[200] = 200;
return res;
}
and add spanGaps: true to the options, the line will be nice and straight, otherwise the way the pixels line up will make it look jagged as it tries to connect each one.
Not sure if this helps with your use case.

Chart JS Fill Between two lines

I am looking for a way to fill between two lines with Chart.js so that it would look like this. I have looked and everything seems to talk about filling between two lines across zero. I also need other lines to fill all the way down like normal. Is this something chart.js can do?
Here is a solution that uses a plugin to fill between two datasets. Supports all line styles and fill shading between multiple lines. To fill between a dataset, use the custom param fillBetweenSet to tell a dataset to fill the area between another dataset.
Fiddle - https://jsfiddle.net/ke5n5LnL/26/
Preview:
Code:
<html>
<div>
<canvas id="demo"></canvas>
</div>
</html>
<script>
var fillBetweenLinesPlugin = {
afterDatasetsDraw: function (chart) {
var ctx = chart.chart.ctx;
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-0'];
var datasets = chart.data.datasets;
ctx.save();
for (var d = 0; d < datasets.length; d++) {
var dataset = datasets[d];
if (dataset.fillBetweenSet == undefined) {
continue;
}
// get meta for both data sets
var meta1 = chart.getDatasetMeta(d);
var meta2 = chart.getDatasetMeta(dataset.fillBetweenSet);
// do not draw fill if one of the datasets is hidden
if (meta1.hidden || meta2.hidden) continue;
// create fill areas in pairs
for (var p = 0; p < meta1.data.length-1;p++) {
// if null skip
if (dataset.data[p] == null || dataset.data[p+1] == null) continue;
ctx.beginPath();
// trace line 1
var curr = meta1.data[p];
var next = meta1.data[p+1];
ctx.moveTo(curr._view.x, curr._view.y);
ctx.lineTo(curr._view.x, curr._view.y);
if (curr._view.steppedLine === true) {
ctx.lineTo(next._view.x, curr._view.y);
ctx.lineTo(next._view.x, next._view.y);
}
else if (next._view.tension === 0) {
ctx.lineTo(next._view.x, next._view.y);
}
else {
ctx.bezierCurveTo(
curr._view.controlPointNextX,
curr._view.controlPointNextY,
next._view.controlPointPreviousX,
next._view.controlPointPreviousY,
next._view.x,
next._view.y
);
}
// connect dataset1 to dataset2
var curr = meta2.data[p+1];
var next = meta2.data[p];
ctx.lineTo(curr._view.x, curr._view.y);
// trace BACKWORDS set2 to complete the box
if (curr._view.steppedLine === true) {
ctx.lineTo(curr._view.x, next._view.y);
ctx.lineTo(next._view.x, next._view.y);
}
else if (next._view.tension === 0) {
ctx.lineTo(next._view.x, next._view.y);
}
else {
// reverse bezier
ctx.bezierCurveTo(
curr._view.controlPointPreviousX,
curr._view.controlPointPreviousY,
next._view.controlPointNextX,
next._view.controlPointNextY,
next._view.x,
next._view.y
);
}
// close the loop and fill with shading
ctx.closePath();
ctx.fillStyle = dataset.fillBetweenColor || "rgba(0,0,0,0.1)";
ctx.fill();
} // end for p loop
}
} // end afterDatasetsDraw
}; // end fillBetweenLinesPlugin
Chart.pluginService.register(fillBetweenLinesPlugin);
var chartData = {
labels: [1, 2, 3, 4, 5,6,7,8],
datasets: [
{
label: "Set 1",
data: [10, 20, null, 40, 30,null,20,40],
borderColor: "#F00",
fill: false,
steppedLine: false,
tension: 0,
fillBetweenSet: 1,
fillBetweenColor: "rgba(255,0,0, 0.2)"
},
{
label: "Set 2",
data: [60, 40, 10, 50, 60,null,50,20],
borderColor: "#00F",
fill: false,
steppedLine: false,
tension: 0.5
},
{
label: "Set 2",
data: [40, 50, 30, 30, 20,null,60,40],
borderColor: "#0D0",
fill: false,
steppedLine: false,
tension: 0,
fillBetweenSet: 1,
fillBetweenColor: "rgba(5,5,255, 0.2)"
}
]
};
var chartOptions = {
responsive: true,
title: {
display: true,
text: 'Demo Fill between lines'
}
};
var chartDemo = new Chart($('#demo').get(0), {
type: 'line',
data: chartData,
options: chartOptions
});
</script>
Setting fill property to +1 of a dataset will set the backgroundColor from this line to the next line in dataset.
datasets: [{
label: 'Systolic Guideline',
data: [],
fill: '+1',
borderColor: '#FFC108',
backgroundColor: 'rgba(255,193,8,0.2)'
},
{
label: 'Diastolic Guideline',
data: [],
fill: true,
borderColor: '#FFC108',
backgroundColor: 'rgba(0,0,0,0)'
}]
On chart.js v2.0 you have this feature now inside. See https://www.chartjs.org/samples/latest/charts/area/line-datasets.html

Google Charts - Hide line when clicking legend key

I'd like to be able to show/hide the lines on my line graph when clicking the relevant key in the legend, is this possible?
To hide show lines on your GWT Visualization LineChart, follow these steps:-
1.Create a DataView object based on an existing DataTable object:
DataTable dataTable = DataTable.create();
DataView dataView = DataView.create(dataTable);
2.Hide the column of the curve/line that you want to hide in the DataView:
dataView.hideColumns(new int[]{<id_of_the_column>});
3.Draw the entire chart again based on the DataView:
chart.draw(dataView, getOptions());
Please note that there is a caveat here, step 3 is a costly step, for us it is taking almost 20-30 sec. for the the new graph to be drawn. But if the data is not large it should be manageable in your context.
Note: You will have to make your own legend with a checkbox and do the above stuff when user checks/unchecks a checkbox.
If you don't need to include scaling and animation then one option is just hide data using lineWidth and areaOpacity values;
<head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script>
function updateTable() {
// quick data - cleaned up for this example real data sources
data = new Array();
data[0] = new Array();
data[0][0] = "Day";
data[0][1] = "Metric 1";
data[0][2] = "Metric 2";
data[0][3] = "Metric 3";
data[1] = new Array();
data[1][0] = 1;
data[1][1] = 200;
data[1][2] = 50;
data[1][3] = 400;
data[2] = new Array();
data[2][0] = 2;
data[2][1] = 440;
data[2][2] = 140;
data[2][3] = 40;
data[3] = new Array();
data[3][0] = 3;
data[3][1] = 300;
data[3][2] = 500;
data[3][3] = 600;
var gdata = google.visualization.arrayToDataTable(data);
var options = {
// title: 'kala',
hAxis: {title: 'Days', titleTextStyle: {color: '#333'}}
,vAxis: {minValue: 0}
,height: 300
,width: 600
,chartArea: {left: 60}
,lineWidth: 2
,series: {0:{color: 'black', areaOpacity: 0.3, lineWidth: 2}
,1:{color: 'red', areaOpacity: 0.3, lineWidth: 2}
,2:{color: 'purple', areaOpacity: 0.3, lineWidth: 2}}
};
var chart = new google.visualization.AreaChart(document.getElementById('my_chart'));
chart.draw(gdata, options);
google.visualization.events.addListener(chart,
'select',
(function (x) { return function () { AreaSelectHander(chart, gdata, options)}})(1));
}
function AreaSelectHander(chart, gdata, options) {
// when ever clicked we enter here
// more code needed to inspect what actually was clicked, now assuming people
// play nicely and click only lables...
var selection = chart.getSelection();
var view = new google.visualization.DataView(gdata);
console.log(options);
// click and data index are one off
i = selection[0].column - 1;
// just simple reverse
if (options.series[i].lineWidth == 0) {
options.series[i].lineWidth = 2;
options.series[i].areaOpacity = 0.3;
}
else {
options.series[i].lineWidth = 0;
options.series[i].areaOpacity = 0.0;
}
chart.draw(gdata, options);
}
</script>
<script type='text/javascript'>
google.load('visualization', '1', {packages:['table', 'corechart']});
google.setOnLoadCallback(updateTable);
</script>
</head>
<body>
<div id='my_chart'></div>
</body>
Following code display goggle line chart and have functionality to hide/show graph line by clicking on legend label. #graph_sales_data is id of div which display chart and sales_data_graph is variable containg record.
function drawChart() {
if (sales_data_graph.length > 1)
{
$('#graph_sales_data').show();
var data = new google.visualization.arrayToDataTable(sales_data_graph);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'graph_sales_data',
dataTable: data,
colors: ['#ea6f09', '#fb250d', '#0ac9c6', '#2680be', '#575bee', '#6bd962', '#ff0000', '#000000'],
options: {
width: 1200,
height: 500,
fontSize: 10,
pointSize: 10
}
});
// create columns array
var columns = [0];
/* the series map is an array of data series
* "column" is the index of the data column to use for the series
* "roleColumns" is an array of column indices corresponding to columns with roles that are associated with this data series
* "display" is a boolean, set to true to make the series visible on the initial draw
*/
var seriesMap = [{
column: 1,
roleColumns: [1],
display: true
}, {
column: 2,
roleColumns: [2],
display: true
}, {
column: 3,
roleColumns: [3],
display: true
}, {
column: 4,
roleColumns: [4],
display: true
}, {
column: 5,
roleColumns: [5],
display: true
}, {
column: 6,
roleColumns: [6],
display: true
}, {
column: 7,
roleColumns: [7],
display: true
}, {
column: 8,
roleColumns: [8],
display: true
}];
var columnsMap = {};
var series = [];
for (var i = 0; i < seriesMap.length; i++) {
var col = seriesMap[i].column;
columnsMap[col] = i;
// set the default series option
series[i] = {};
if (seriesMap[i].display) {
// if the column is the domain column or in the default list, display the series
columns.push(col);
}
else {
// otherwise, hide it
columns.push({
label: data.getColumnLabel(col),
type: data.getColumnType(col),
sourceColumn: col,
calc: function() {
return null;
}
});
// backup the default color (if set)
if (typeof(series[i].color) !== 'undefined') {
series[i].backupColor = series[i].color;
}
series[i].color = '#CCCCCC';
}
for (var j = 0; j < seriesMap[i].roleColumns.length; j++) {
//columns.push(seriesMap[i].roleColumns[j]);
}
}
chart.setOption('series', series);
function showHideSeries() {
var sel = chart.getChart().getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (sel[0].row == null) {
var col = sel[0].column;
if (typeof(columns[col]) == 'number') {
var src = columns[col];
// hide the data series
columns[col] = {
label: data.getColumnLabel(src),
type: data.getColumnType(src),
sourceColumn: src,
calc: function() {
return null;
}
};
// grey out the legend entry
series[columnsMap[src]].color = '#CCCCCC';
}
else {
var src = columns[col].sourceColumn;
// show the data series
columns[col] = src;
series[columnsMap[src]].color = null;
}
var view = chart.getView() || {};
view.columns = columns;
chart.setView(view);
chart.draw();
}
}
}
google.visualization.events.addListener(chart, 'select', showHideSeries);
// create a view with the default columns
var view = {
columns: columns
};
chart.draw();
}
else
{
$('#graph_sales_data').hide();
}
}