Change color in chart based on data

Hi - I have a chart (see below) that I had different colors set up for the bars. They now want them all green except if there is a negative result. Is there a way I can change the bar color if it is negative?

var chartData = [
{
‘value_label’ : ‘QTR’,
‘values_1’ : record.tables[“ROR”][0].fields[‘QtrPct’]== “999.00” ? 0 : record.tables[“ROR”][0].fields[‘QtrPct’],
‘color’:‘#6da141
},
{
‘value_label’ : ‘YTD’,
‘values_1’ : record.tables[“ROR”][0].fields[‘YtdPct’] == “999.00” ? 0 : record.tables[“ROR”][0].fields[‘YtdPct’],
‘color’: ‘#6da141
},
{
‘value_label’ : ‘1 Year’,
‘values_1’ : record.tables[“ROR”][0].fields[‘Yr1Pct’]== “999.00” ? 0 : record.tables[“ROR”][0].fields[‘Yr1Pct’],
‘color’: ‘#6da141
},
{
‘value_label’ : ‘3 Year’,
‘values_1’ : record.tables[“ROR”][0].fields[‘Yr3Pct’]== “999.00” ? 0 : record.tables[“ROR”][0].fields[‘Yr3Pct’],
‘color’: ‘#6da141
},
{
‘value_label’ : ‘5 Year’,
‘values_1’ : record.tables[“ROR”][0].fields[‘Yr5Pct’]== “999.00” ? 0 : record.tables[“ROR”][0].fields[‘Yr5Pct’],
‘color’: ‘#6da141
}
];

var config = {
type : ‘serial’,
rotate: ‘true’,
dataProvider : chartData,
categoryField : ‘value_label’,
categoryAxis: {
tickLength: 0
},
graphs : [
{
title: ‘’,
valueField: “values_1”,
type: “column”,
fillAlphas: 1,
lineAlpha: 0,
gridThickness: 0,
fillColorsField: “color”
}
],
valueAxes: [
{
tickLength: 0,
gridThickness: 0
}
]

};
results.attr(‘data-amchart’, JSON.stringify(config));

Thank you

Hi @ahaddad,

You already added some logic for ‘values_1’, you can do something similar for ‘color’.

There is a lot of repetition in the code you posted though. You could consider refactoring it so that it gets a bit easier to maintain:

function getData(field, label) {
	const value = record.tables['ROR'][0].fields[field];
	return {
		'value_label': label,
		'values_1': value == '999.00' ? 0 : value,
		'color': value < 0 ? 'red' : '#6da141'
	};
}

var chartData = [
	getData('QtrPct', 'QTR'),
	getData('YtdPct', 'YTD'),
	getData('Yr1Pct', '1 Year'),
	getData('Yr3Pct', '3 Year'),
	getData('Yr5Pct', '5 Year')
];

...
1 Like

Thank you! This works great!! Yes, this code was created like 5 years ago when I first started to use connect. As I have to make changes to templates, I am changing code also to help make it more efficient. Thanks again.