Google Charts - Material Bar Chart, Convert Options - javascript

I am trying to use Material Bar Chart, because i want to change K format for thousands at the Vaxis data. I want to show as 1000 not like 1k. When I use the following code for the chart, it seems okey, but i cannot customize Vaxis;
<script>
Array.prototype.insert = function ( index, item ) {
this.splice( index, 0, item );
};
function all(arr2,test){
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
if(arrGrp[0].length == 2)
{
arr2.push([' ', null]);
}
var data = google.visualization.arrayToDataTable(arr2);
console.log("ARR: " + arr2);
var options = {
title: 'Min: ' + min +' Max: ' + max ,
bars:'vertical',
bar: {groupWidth: "25%"},
height: 400,
vAxis: {
format: 'decimal',
minValue: min,
maxValue: max,
viewWindowMode : 'explicit',
viewWindow: {
max:max,
min:min
},}};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
var arrGrp=[];
</script>
And I populate my data as follows;
#{
var grpHeader2 = Model.GroupBy(r => new { r.GradeId, r.Grade }).ToList();
<script>
var arr = [];
var rowIndex=0;
arr.insert(rowIndex,'Date');
rowIndex++;
#foreach (var grpHeaderItem in grpHeader2)
{
<text>
arr.insert(rowIndex,'#(Html.Raw(grpHeaderItem.Key.Grade))');
rowIndex++;
</text>
}
arrGrp.push(arr);
max='#(Model.Max(r=>r.MaxScore).HasValue ? Model.Max(r => r.MaxScore) : -1 )';
min='#(Model.Min(r=>r.MinScore).HasValue ? Model.Min(r => r.MinScore) : -1 )';
</script>
}
#foreach (var item in Model.GroupBy(r => new { r.PlannedDate }))
{
<script>
var arr = [];
var rowIndex=0;
#*arr.insert(rowIndex,new Date(#item.Key.PlannedDate.Year,#item.Key.PlannedDate.Month,#item.Key.PlannedDate.Day));*#
arr.insert(rowIndex,'#item.Key.PlannedDate.ToString("dd.MM.yyyy")');
rowIndex++;
#foreach (var grpHeaderItem in grpHeader2)
{
<text>
arr.insert(rowIndex,#(Model.Where(r=>r.PlannedDate == item.Key.PlannedDate && grpHeaderItem.Key.GradeId == r.GradeId).Select(r=>r.GradeMin).FirstOrDefault()));
rowIndex++;
</text>
}
arrGrp.push(arr);
</script>
}
#{
<script>
all(arrGrp,'#(Html.Raw(ViewBag.Exam))');
</script>
Screen shot is [1]: https://imgyukle.com/i/1.xElyj "before - working but no customization"
But when change code
chart.draw(data, options);
to
chart.draw(data, google.charts.Bar.convertOptions(options));
It looks like; [2]: https://imgyukle.com/i/2.xE348 "nothing working"
Can someone please help me what is wrong with that?

when you draw the chart without --> google.charts.Bar.convertOptions,
the chart ignores the options for --> vAxis.viewWindow.min & max,
so the chart draws fine...
google.charts.load('current', {
packages:['bar']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Date', 'Reading', 'Writing', 'Reading & Writing', 'Math', 'Total'],
['07.08.2018', 220, 230, 450, 610, 1060]
]);
var min = -1;
var max = -1;
var options = {
title: 'Min: ' + min +' Max: ' + max ,
bars:'vertical',
bar: {groupWidth: "25%"},
height: 400,
vAxis: {
format: 'decimal',
minValue: min,
maxValue: max,
viewWindowMode : 'explicit',
viewWindow: {
max:max,
min:min
}
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, (options));
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
when you draw the chart with --> google.charts.Bar.convertOptions,
it uses the min & max options, but according to the picture,
min & max are both set to --> -1,
there are no rows that meet this criteria,
so the chart is blank...
google.charts.load('current', {
packages:['bar']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Date', 'Reading', 'Writing', 'Reading & Writing', 'Math', 'Total'],
['07.08.2018', 220, 230, 450, 610, 1060]
]);
var min = -1;
var max = -1;
var options = {
title: 'Min: ' + min +' Max: ' + max ,
bars:'vertical',
bar: {groupWidth: "25%"},
height: 400,
vAxis: {
format: 'decimal',
minValue: min,
maxValue: max,
viewWindowMode : 'explicit',
viewWindow: {
max:max,
min:min
}
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: there are several options that are not supported by Material charts.
see --> Tracking Issue for Material Chart Feature Parity
this includes --> vAxis.minValue, vAxis.maxValue, & vAxis.format
but vAxis.viewWindow.min & max work, and is the same as vAxis.minValue & vAxis.maxValue
to format the y-axis, use --> vAxes (with an e) -- format each axis separately, here you only have one
vAxes: {
0: {
format: 'decimal'
}
}
see following working snippet...
google.charts.load('current', {
packages:['bar']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Date', 'Reading', 'Writing', 'Reading & Writing', 'Math', 'Total'],
['07.08.2018', 220, 230, 450, 610, 1060]
]);
var min = 0;
var max = 1200;
var options = {
title: 'Min: ' + min +' Max: ' + max ,
bars:'vertical',
bar: {groupWidth: "25%"},
height: 400,
vAxis: {
viewWindow: {
max:max,
min:min
}
},
vAxes: {
0: {
format: 'decimal'
}
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

ColumnChart not show all string labels

I have The following problem related with ColumnChart (https://developers.google.com/chart/interactive/docs/gallery/columnchart).
If the label (when you mouse hover into any columns that looks like a tooltip) is set as a number, all 2000 items shows correctly. But if the label is set as a string it only shows 289 items in the chart and it is missing 1711 columns for an unknown reason.
I have this code (Label set with String, only shows 289 items instead of 2000):
http://jsfiddle.net/c809mbjx/11/
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string' ,'Day');
data.addColumn('number', 'Matches');
var dataArray = []
let number = 2000
data.addRows(number);
for (var i = 0; i < number;i++) {
data.setCell(i,0,"aaa_"+i)
data.setCell(i,1,i);
}
//var data = new google.visualization.arrayToDataTable(dataArray);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
colors: ['#0095e8'],
hAxis: {textPosition: 'none'},
vAxis: {minValue: 0, viewWindow: {min: 0}},
legend: 'none',
animation: {duration: 10000, easing: 'out'}
};
chart.draw(view, options);
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawChart});
And this code (Label set with Number and works correctly):
http://jsfiddle.net/c809mbjx/12/
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number' ,'Day');
data.addColumn('number', 'Matches');
var dataArray = []
let number = 2000
data.addRows(number);
for (var i = 0; i < number;i++) {
data.setCell(i,0,i)
data.setCell(i,1,i);
}
//var data = new google.visualization.arrayToDataTable(dataArray);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
colors: ['#0095e8'],
hAxis: {textPosition: 'none'},
vAxis: {minValue: 0, viewWindow: {min: 0}},
legend: 'none',
animation: {duration: 10000, easing: 'out'}
};
chart.draw(view, options);
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawChart});
we can use numbers on the x-axis and still display the string on the tooltip.
which can be accomplished by setting the last argument of the setCell method --> formattedValue
setCell(rowIndex, columnIndex, value, formattedValue)
the tooltip will display the formatted value by default.
so we provide the number as the value, and our own string as the formatted value.
data.setCell(i,0,i,"aaa_"+i);
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number' ,'Day');
data.addColumn('number', 'Matches');
let number = 2000;
data.addRows(number);
for (var i = 0; i < number;i++) {
data.setCell(i,0,i,"aaa_"+i);
data.setCell(i,1,i);
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
colors: ['#0095e8'],
hAxis: {textPosition: 'none'},
vAxis: {minValue: 0, viewWindow: {min: 0}},
legend: 'none',
animation: {duration: 10000, easing: 'out'}
};
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
note: the version of google charts loaded using jsapi has been deprecated and should no longer be used.
instead, use loader.js, this will only change the load statement.
see above snippet...

How to place an icon inside Google ColumnChart

I have columnchart bar which has one column and I wanna place an icon top of the bar.This bar is dynamically changing as randomly.I checked some sources on the internet and Google Chart API but couldn't find a solution.Is there any way to do that?Below you can see the code belongs to my chart
Here it's demo to give you idea about my Grid and Chart also
https://stackblitz.com/edit/angular-pt2kha?file=app/grid-list-overview-example.html
Here what I expect to see
What I tried below to generate this Column Chart below
TS File
title= 'Temperature';
type = 'ColumnChart';
data= [['',25]];
columnNames= ['Element', 'Temperature'];
options= {
backgroundColor: '#fafafa',
legend: {position: 'none'},
animation: {
duration: 250,
easing: 'ease-in-out',
startup: true,
},
bar: {
groupWidth: 50
},
hAxis: {
baselineColor: 'none',
ticks: []
},
vAxis: {
baselineColor: 'none',
ticks: [],
viewWindow: {
max:40,
min:0
}
}
}
width=100;
height=300;
ngOnInit()
{
interval(2000).subscribe(()=>{
this.data = [
['', (Math.random() * 41)],
];
});
}
HTML File
<div style="border-style:solid;border-width:1px;">
<google-chart #chart
[title]="title"
[type]="type"
[data]="data"
[columnNames]="columnNames"
[options]="options"
[width]="width"
[height]="height"
>
</google-chart>
</div>
you can add icons using chart methods getChartLayoutInterface() & getBoundingBox()
on the chart's 'ready' event, find the position of the bar,
then place the image.
although not angular, it will work the same,
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'X');
data.addColumn('number', 'Y');
data.addRows([
[{v: 'a', p: {thumb: 'clone_old.png'}}, 20],
[{v: 'b', p: {thumb: 'boba_fett.png'}}, 15],
[{v: 'c', p: {thumb: 'jango_fett.png'}}, 30],
[{v: 'd', p: {thumb: 'clone_3.png'}}, 5],
[{v: 'e', p: {thumb: 'clone_2.png'}}, 25]
]);
var options = {
legend: 'none'
};
var container = document.getElementById('chart_div');
var containerBounds = container.getBoundingClientRect();
var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var chartLayout = chart.getChartLayoutInterface();
for (var i = 0; i < data.getNumberOfRows(); i++) {
var barBounds = chartLayout.getBoundingBox('bar#0#' + i);
var path = 'http://findicons.com/files/icons/512/star_wars/32/';
var thumb = container.appendChild(document.createElement('img'));
thumb.src = path + data.getProperty(i, 0, 'thumb');
thumb.style.position = 'absolute';
thumb.style.top = (barBounds.top + containerBounds.top - 40) + 'px';
thumb.style.left = (barBounds.left + containerBounds.left + (barBounds.width / 2) - 16) + 'px';
}
});
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
`

Google chart stacked bar get key name when onclick

google.charts.load('current', { packages: ['corechart', 'bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['DATA', 'L', 'P'],
['PCX', 18, 21],['PCG', 131, 34],['PCO', 9, 3],['PGD', 441, 269],['PAH', 1, 1],['POD', 8, 5],['PCT', 80, 180],['PDD', 1, 7],['PZZ', 3, 8],['PKK', 461, 580],['PBI', 494, 248],['PKI', 2, 5],['PKL', 5, 1] ]);
var options = {
isStacked: 'percent',
legend: { position: 'top' },
chartArea: {
left: 40,
width: '100%',
height: '75%'
},
vAxis: {
minValue: 0,
},
hAxis: {
textStyle: { fontSize: 7 }
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('DataChart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
var mydata = data.getValue(selection[0].row,0);
alert(mydata);
//i want get key data L when klik stacked data L or P when klik stacked data P, because i want to send data
chart.setSelection([]);
}
}
}
$(window).resize(function () {
drawChart();
});
svg > g > g:last-child { pointer-events: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="DataChart" ></div>
Hello, i have a create stacked bar from google chart plugin, i want to get data when i'm click slice bar (red or blue) when i click red i get data "P" if i click blue get data "L" this demo in Js Fiddle
i'm already get data name data like PCX,PCG,PGD etc but i want get data "L" if click blue color and get data "P" when click red color. Help me thank's
to get the column label, use data table method --> getColumnLabel(colIndex)
pass the column property from the selection...
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
// get column label
var colLabel = data.getColumnLabel(selection[0].column);
var mydata = data.getValue(selection[0].row,0);
console.log(colLabel + ': ' + mydata);
chart.setSelection([]);
}
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
$(window).resize(drawChart);
drawChart();
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['DATA', 'L', 'P'],
['PCX', 18, 21],['PCG', 131, 34],['PCO', 9, 3],['PGD', 441, 269],['PAH', 1, 1],['POD', 8, 5],['PCT', 80, 180],['PDD', 1, 7],['PZZ', 3, 8],['PKK', 461, 580],['PBI', 494, 248],['PKI', 2, 5],['PKL', 5, 1] ]);
var options = {
isStacked: 'percent',
legend: { position: 'top' },
chartArea: {
left: 40,
width: '100%',
height: '75%'
},
vAxis: {
minValue: 0,
},
hAxis: {
textStyle: { fontSize: 7 }
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('DataChart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
var colLabel = data.getColumnLabel(selection[0].column);
var mydata = data.getValue(selection[0].row,0);
console.log(colLabel + ': ' + mydata);
chart.setSelection([]);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="DataChart"></div>
In google charts document,
"If both row and column are specified, the selected element is a cell. If only row is specified, the selected element is a row. If only column is specified, the selected element is a column."
(https://developers.google.com/chart/interactive/docs/events)
In your demo, when clicking blueBar(L), selection[0].column will be 1 and the other(redBar(P)) will be 2.
Thus you can get P/L in selectHandler
var data = ['DATA', 'L', 'P']
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
var temp = selection[0].column
console.log(data[temp]) // temp = 1 will be 'L'; temp = 2 will be 'P'
}
}

Google chart - role: annotation in candlestick bar [duplicate]

i'm trying to use Google Chart API for building an Waterfall chart. I noticed that Candlestick/Waterfall charts are not supporting the annotations.
See this jsfiddle sample
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'MinimumLevel');
data.addColumn('number', 'MinimumLevel1');
data.addColumn('number', 'MaximumLevel');
data.addColumn('number', 'MaximumLevel1');
data.addColumn({type: 'number', role: 'tooltip'});
data.addColumn({type: 'string', role: 'style'});
data.addColumn({type: 'number', role: 'annotation'});
data.addRow(['Category 1', 0 , 0, 5, 5, 5,'gray',5]);
data.addRow(['Category 2', 5 , 5, 10, 10, 10,'red',10]);
data.addRow(['Category 3', 10 , 10, 15, 15, 15,'blue',15]);
data.addRow(['Category 4', 15 , 15, 10, 10, 10,'yellow',10]);
data.addRow(['Category 5', 10 , 10, 5, 5, 5,'gray',5]);
var options = {
legend: 'none',
bar: { groupWidth: '60%' } // Remove space between bars.
};
var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I would like to put the value of the 5th column at the top of every candlestick.
It should look like this :
Is there a way to do this?
Thanks
I add annotations to candlestick charts by adding annotations to a hidden scatter plot. You can set exactly where you want the annotations to sit by changing the plot.
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Low');
data.addColumn('number', 'Open');
data.addColumn('number', 'Close');
data.addColumn('number', 'High');
data.addColumn('number'); //scatter plot for annotations
data.addColumn({ type: 'string', role: 'annotation' }); // annotation role col.
data.addColumn({ type: 'string', role: 'annotationText' }); // annotationText col.
var high, low, open, close = 160;
for (var i = 0; i < 10; i++) {
open = close;
close += ~~(Math.random() * 10) * Math.pow(-1, ~~(Math.random() * 2));
high = Math.max(open, close) + ~~(Math.random() * 10);
low = Math.min(open, close) - ~~(Math.random() * 10);
annotation = '$' + close;
annotation_text = 'Close price: $' + close;
data.addRow([new Date(2014, 0, i + 1), low, open, close, high, high, annotation, annotation_text]);
}
var view = new google.visualization.DataView(data);
var chart = new google.visualization.ComboChart(document.querySelector('#chart_div'));
chart.draw(view, {
height: 400,
width: 600,
explorer: {},
chartArea: {
left: '7%',
width: '70%'
},
series: {
0: {
color: 'black',
type: 'candlesticks',
},
1: {
type: 'scatter',
pointSize: 0,
targetAxisIndex: 0,
},
},
candlestick: {
color: '#a52714',
fallingColor: { strokeWidth: 0, fill: '#a52714' }, // red
risingColor: { strokeWidth: 0, fill: '#0f9d58' } // green
},
});
}
<script type="text/javascript"src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
just so happens, i ran into the same problem this week
so I added my own annotations, during the 'animationfinish' event
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var dataChart = new google.visualization.DataTable({"cols":[{"label":"Category","type":"string"},{"label":"Bottom 1","type":"number"},{"label":"Bottom 2","type":"number"},{"label":"Top 1","type":"number"},{"label":"Top 2","type":"number"},{"role":"style","type":"string","p":{"role":"style"}}],"rows":[{"c":[{"v":"Budget"},{"v":0},{"v":0},{"v":22707893.613},{"v":22707893.613},{"v":"#007fff"}]},{"c":[{"v":"Contract Labor"},{"v":22707893.613},{"v":22707893.613},{"v":22534350.429},{"v":22534350.429},{"v":"#1e8449"}]},{"c":[{"v":"Contract Non Labor"},{"v":22534350.429},{"v":22534350.429},{"v":22930956.493},{"v":22930956.493},{"v":"#922b21"}]},{"c":[{"v":"Materials and Equipment"},{"v":22930956.493},{"v":22930956.493},{"v":22800059.612},{"v":22800059.612},{"v":"#1e8449"}]},{"c":[{"v":"Other"},{"v":22800059.612},{"v":22800059.612},{"v":21993391.103},{"v":21993391.103},{"v":"#1e8449"}]},{"c":[{"v":"Labor"},{"v":21993391.103},{"v":21993391.103},{"v":21546003.177999996},{"v":21546003.177999996},{"v":"#1e8449"}]},{"c":[{"v":"Travel"},{"v":21546003.177999996},{"v":21546003.177999996},{"v":21533258.930999994},{"v":21533258.930999994},{"v":"#1e8449"}]},{"c":[{"v":"Training"},{"v":21533258.930999994},{"v":21533258.930999994},{"v":21550964.529999994},{"v":21550964.529999994},{"v":"#922b21"}]},{"c":[{"v":"Actual"},{"v":0},{"v":0},{"v":21550964.52999999},{"v":21550964.52999999},{"v":"#007fff"}]}]});
var waterFallChart = new google.visualization.ChartWrapper({
chartType: 'CandlestickChart',
containerId: 'chart_div',
dataTable: dataChart,
options: {
animation: {
duration: 1500,
easing: 'inAndOut',
startup: true
},
backgroundColor: 'transparent',
bar: {
groupWidth: '85%'
},
chartArea: {
backgroundColor: 'transparent',
height: 210,
left: 60,
top: 24,
width: '100%'
},
hAxis: {
slantedText: false,
textStyle: {
color: '#616161',
fontSize: 9
}
},
height: 272,
legend: 'none',
tooltip: {
isHtml: true,
trigger: 'both'
},
vAxis: {
format: 'short',
gridlines: {
count: -1
},
textStyle: {
color: '#616161'
},
viewWindow: {
max: 24000000,
min: 16000000
}
},
width: '100%'
}
});
google.visualization.events.addOneTimeListener(waterFallChart, 'ready', function () {
google.visualization.events.addListener(waterFallChart.getChart(), 'animationfinish', function () {
var annotation;
var chartLayout;
var container;
var numberFormatShort;
var positionY;
var positionX;
var rowBalance;
var rowBottom;
var rowFormattedValue;
var rowIndex;
var rowTop;
var rowValue;
var rowWidth;
container = document.getElementById(waterFallChart.getContainerId());
chartLayout = waterFallChart.getChart().getChartLayoutInterface();
numberFormatShort = new google.visualization.NumberFormat({
pattern: 'short'
});
rowIndex = 0;
Array.prototype.forEach.call(container.getElementsByTagName('rect'), function(rect) {
switch (rect.getAttribute('fill')) {
// use colors to identify bars
case '#922b21':
case '#1e8449':
case '#007fff':
rowWidth = parseFloat(rect.getAttribute('width'));
if (rowWidth > 2) {
rowBottom = waterFallChart.getDataTable().getValue(rowIndex, 1);
rowTop = waterFallChart.getDataTable().getValue(rowIndex, 3);
rowValue = rowTop - rowBottom;
rowBalance = Math.max(rowBottom, rowTop);
positionY = chartLayout.getYLocation(rowBalance) - 6;
positionX = parseFloat(rect.getAttribute('x'));
rowFormattedValue = numberFormatShort.formatValue(rowValue);
if (rowValue < 0) {
rowFormattedValue = rowFormattedValue.replace('-', '');
rowFormattedValue = '(' + rowFormattedValue + ')';
}
annotation = container.getElementsByTagName('svg')[0].appendChild(container.getElementsByTagName('text')[0].cloneNode(true));
$(annotation).text(rowFormattedValue);
annotation.setAttribute('x', (positionX + (rowWidth / 2)));
annotation.setAttribute('y', positionY);
annotation.setAttribute('font-weight', 'bold');
rowIndex++;
}
break;
}
});
});
});
$(window).resize(function() {
waterFallChart.draw();
});
waterFallChart.draw();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Line Chart: Change color when line down

https://developers.google.com/chart/interactive/docs/gallery/linechart
Hello, guys, I would like to know that is there a way to change the color of the line when it is moving down. I have googled but I was not able to find anything.
like e.g the line graph is moving upwards it's ok as soon as the graph line tilts downward than that downward should only be red. If after that it moves upward then the upward line should not be red.
Here is a screenshot of what I'm trying to obtain:
http://imgur.com/a/GuWDx
If anybody knows this please help me
Here is my code of what am I doing right now:
function draw_chart(chart_data, id, action)
{
var url = base_url + "controller/function/" + id ;
statData = getAjax(url, '', false, 'json');
minimum = '';
maximum = '';
upside = '';
if (statData.min) {
minimum = statData.min;
}
if (statData.max) {
maximum = statData.max;
}
if (statData.upside == '1') {
upside = -1;
}
value = $("#value_" + id).val();
var name = $('#name_' + id).val();
var names = [];
if (value == 2) {
var names = name.split('/');
} else {
names[0] = name;
}
title = $("#name_" + id).val();
google.load('visualization', '1.1', {packages: ['line', 'corechart']});
format = $("#format-select_" + id + " option:selected").val();
if (statData.row[0].type == 'currency') {
format = '$#';
}
var options = {
title: title,
width: 820,
height: 500,
titlePosition: 'none',
legend: 'none',
lineWidth: 3,
annotation: {
0: { style: "line"},
1: { style: "line"}
},
series: {0: { style: "area"} , 1: {type: "area"}},
animation: {duration: 1000, easing: 'in'},
strictFirstColumnType: true,
fontColor: "#333333",
fontSize: "12px",
colors: ["#5AA023", "#3F5F9F" , ""],
pointSize: 6,
fontSize: 11,
enableEvents: true,
forceIFrame: false,
tooltip: {showColorCode: false, },
vAxis: {
gridlines:{color: "#E6E6E6"},
textStyle:{color: "#666666"},
baselineColor: "#CACACA",
format: format,
viewWindow:{
min: minimum,
max: maximum
},
direction: upside,
},
hAxis: {gridlines:{color: "#E6E6E6" , count:chart_data.length},
baselineColor: "#CACACA",
textStyle:{color: "#666666"},
format: "MMM dd yyyy",
textPosition: "out",
slantedText: true,
},
chartArea: {height: 420, width: 750, top: 14, left: 45, right: 0}
};
if (action && action == "update") {
//alert(action);
}
else {
var chart_div = document.getElementById('chart'+id);
var chart_div1 = document.getElementById('chart1'+id);
var chart = new google.visualization.LineChart(chart_div);
google.visualization.events.addListener(chart, 'select', clickHandler);
data = new google.visualization.DataTable();
data.addColumn('string', 'Season Start Date');
data.addColumn({type: 'string', role: 'annotation'});
data.addColumn('number', names[0].trim());
if (value == 2) {
data.addColumn('number', names[1].trim());
for (i = 0; i < chart_data.length; i++)
data.insertRows(0, [[new Date(chart_data[i].date), parseInt(chart_data[i].val), parseInt(chart_data[i].val1)]]);
}
else {
for (i = 0; i < chart_data.length; i++) {
if (!chart_data[i].quarter) {
date = chart_data[i].date.split('-');
month = getMonthName(date[1]);
day = date[2];
year = date[0];
data.insertRows(0, [[month+' '+day+' '+year , '.' , parseInt(chart_data[i].val) ]]);
} else {
data.insertRows(0, [[chart_data[i].quarter , '.' , parseInt(chart_data[i].val) ]]);
}
}
}
}
}
if (statData.row[0].type == 'currency') {
var formatter = new google.visualization.NumberFormat({prefix: '$'});
formatter.format(data, 1);
}
var dataView = new google.visualization.DataView(data);
dataView.setColumns([
// reference existing columns by index
0, 1,
// add function for line color
{
calc: function(data, row) {
console.log("ok world!");
var colorDown = '#0000FF';
var colorUp = 'green';
if ((row === 0) && (data.getValue(row, 1) < data.getValue(row + 1, 1))) {
return colorDown;
} else if ((row > 0) && (data.getValue(row - 1, 1) < data.getValue(row, 1))) {
return colorDown;
}
return colorUp;
},
type: 'string',
role: 'style'
}
]);
chart.draw(dataView, options);
use a DataView and setColumns to provide a function that determines line direction
and returns the appropriate line color
see following working snippet...
google.charts.load('current', {
callback: drawLineColors,
packages: ['corechart']
});
function drawLineColors() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Y');
data.addRows([
[0, 2000],
[3, 1700],
[6, 1400],
[9, 2500],
[12, 3000],
[15, 4700],
[18, 2200],
[21, 1500],
[24, 1200],
[27, 1800],
[30, 2600],
[33, 2800],
[36, 3000],
[39, 2300],
[42, 2000],
[45, 4000]
]);
var options = {
curveType: 'function',
height: 200,
legend: {
position: 'top'
}
};
var dataView = new google.visualization.DataView(data);
dataView.setColumns([
// reference existing columns by index
0, 1,
// add function for line color
{
calc: function(data, row) {
var colorDown = '#0000FF';
var colorUp = '#FF0000';
if ((row === 0) && (data.getValue(row, 1) < data.getValue(row + 1, 1))) {
return colorDown;
} else if ((row > 0) && (data.getValue(row - 1, 1) < data.getValue(row, 1))) {
return colorDown;
}
return colorUp;
},
type: 'string',
role: 'style'
}
]);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(dataView, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Categories

Resources