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>
Related
I am using google charts and showing 3 tooltips by default when chart is loaded for that i have used
tooltip: { trigger: 'selection' },
aggregationTarget: 'none',
selectionMode: 'multiple'
Every thing is working fine but when the points get very close to each other like (1,1) and (1,1.5) the tool tips comes over each other please see this image. Is there any option or a way to overcome this.
google.charts.load('current', {
packages: ['corechart']
}).then(drawScatterChart);
function drawScatterChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'brand');
data.addColumn('number', 'store');
data.addColumn({
type: 'string',
role: 'tooltip'
});
data.addColumn({
type: 'string',
role: 'style'
});
var datarows = "";
var json = JSON.parse('[{"store":4.73977695167286,"brand":4.95353159851301,"empty":false,"tooltip":true,"tooltiptext":"Alpha Bravo"},{"store":0.362526138475839,"brand":0.835487337360595,"empty":false,"tooltip":true,"tooltiptext":"Avg. For Age"},{"store":0.598803222730479,"brand":1.14256989262171,"empty":false,"tooltip":true,"tooltiptext":"Franchisee Avg."},{"store":0.0929368029739777,"brand":0.288104089219331,"empty":false,"tooltip":true,"tooltiptext":"Andrew Richardson"},{"store":4.64684014869888,"brand":7.00743494423792,"empty":false,"tooltip":true,"tooltiptext":"April Singer"},{"store":4.64684014869888,"brand":7.00743494423792,"empty":false,"tooltip":true,"tooltiptext":"April Singer"}]');
$.each(json, function(ind, ele) {
//Every row given must be either null or an array.
var arr = [];
//'point {stroke-color: #A3A3A3; stroke-width: 0; fill-color: none;');/
if (ele.empty == true) {
arr.push(ele.brand, ele.store, "", 'point {stroke-color: #A3A3A3; stroke-width: 0; fill-color: none;'); //" Franchise Avg. ");fill-color: #a52714;
} else {
if (ele.tooltip == true) {
datarows += ind + ",";
}
arr.push(ele.brand, ele.store, ele.tooltiptext, 'point {stroke-color: #A3A3A3; stroke-width: 1'); //" Franchise Avg. ");fill-color: #a52714;
}
data.addRows([arr]);
});
var container = document.getElementById('chart_div');
var chart = new google.visualization.ScatterChart(container);
var options = {
width: 500,
height: 440,
legend: 'none',
hAxis: {
title: 'Brand Engagement',
gridlines: {
count: 11
}
}, //, minValue: 0
vAxis: {
title: 'Performance',
gridlines: {
count: 11
}
}, //, minValue: 0
backgroundColor: 'none',
colors: ['#fff'],
chartArea: {
left: 50,
top: 20,
width: "80%",
height: "87%"
},
tooltip: {
isHtml: true,
trigger: 'selection'
},
aggregationTarget: 'none',
pointSize: 5,
selectionMode: 'multiple',
};
google.visualization.events.addListener(chart, 'ready', setChartSelection);
function setChartSelection() {
var arrRows = datarows.split(",");
chart.setSelection([{
row: arrRows[0],
column: 1
},
{
row: arrRows[1],
column: 1
},
{
row: arrRows[2],
column: 1
}
]);
}
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chart_div" style="float: left;">
</div>
there are no options you can set to avoid overlap...
a possible solution would be to use the explorer option to pan and zoom
explorer: {
actions: ['dragToZoom', 'rightClickToReset']
}
see following working snippet, when the chart loads,
use the mouse to draw a square around the two points on the lower left,
once zoomed, both tooltips are displayed fully...
google.charts.load('current', {
packages: ['corechart']
}).then(drawScatterChart);
function drawScatterChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'brand');
data.addColumn('number', 'store');
data.addColumn({
type: 'string',
role: 'tooltip'
});
data.addColumn({
type: 'string',
role: 'style'
});
var datarows = "";
var json = JSON.parse('[{"store":4.73977695167286,"brand":4.95353159851301,"empty":false,"tooltip":true,"tooltiptext":"Alpha Bravo"},{"store":0.362526138475839,"brand":0.835487337360595,"empty":false,"tooltip":true,"tooltiptext":"Avg. For Age"},{"store":0.598803222730479,"brand":1.14256989262171,"empty":false,"tooltip":true,"tooltiptext":"Franchisee Avg."},{"store":0.0929368029739777,"brand":0.288104089219331,"empty":false,"tooltip":true,"tooltiptext":"Andrew Richardson"},{"store":4.64684014869888,"brand":7.00743494423792,"empty":false,"tooltip":true,"tooltiptext":"April Singer"},{"store":4.64684014869888,"brand":7.00743494423792,"empty":false,"tooltip":true,"tooltiptext":"April Singer"}]');
$.each(json, function(ind, ele) {
//Every row given must be either null or an array.
var arr = [];
//'point {stroke-color: #A3A3A3; stroke-width: 0; fill-color: none;');/
if (ele.empty == true) {
arr.push(ele.brand, ele.store, "", 'point {stroke-color: #A3A3A3; stroke-width: 0; fill-color: none;'); //" Franchise Avg. ");fill-color: #a52714;
} else {
if (ele.tooltip == true) {
datarows += ind + ",";
}
arr.push(ele.brand, ele.store, ele.tooltiptext, 'point {stroke-color: #A3A3A3; stroke-width: 1'); //" Franchise Avg. ");fill-color: #a52714;
}
data.addRows([arr]);
});
var container = document.getElementById('chart_div');
var chart = new google.visualization.ScatterChart(container);
var options = {
width: 500,
height: 440,
legend: 'none',
hAxis: {
title: 'Brand Engagement',
gridlines: {
count: 11
}
}, //, minValue: 0
vAxis: {
title: 'Performance',
gridlines: {
count: 11
}
}, //, minValue: 0
backgroundColor: 'none',
colors: ['#fff'],
chartArea: {
left: 50,
top: 20,
width: "80%",
height: "87%"
},
tooltip: {
isHtml: true,
trigger: 'selection'
},
aggregationTarget: 'none',
pointSize: 5,
selectionMode: 'multiple',
explorer: {
actions: ['dragToZoom', 'rightClickToReset']
}
};
google.visualization.events.addListener(chart, 'ready', setChartSelection);
function setChartSelection() {
var arrRows = datarows.split(",");
chart.setSelection([{
row: arrRows[0],
column: 1
},
{
row: arrRows[1],
column: 1
},
{
row: arrRows[2],
column: 1
}
]);
}
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chart_div" style="float: left;">
</div>
I am trying to create a dynamic bar chart in a MVC application in Visual Studio
<input type="button" value="Add Column" onclick="add('Work',20)" class="btn btn-default btn-sm" />
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script>
var myObj = { "Elicit": 16, "Design": 23, "Code": 17, "Test": 24, "Deploy": 20 };
var myJSON = JSON.stringify(myObj);
var obj2 = JSON.parse(myJSON);
var v1 = obj2.Elicit;
var v2 = obj2.Design;
var v3 = obj2.Code;
var v4 = obj2.Test;
var v5 = obj2.Deploy;
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawTrendlines);
function drawTrendlines() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Items');
data.addColumn('number', 'Sales');
data.addRows([
['Elicitation', v1],
['Design', v2],
['Code', v3],
['Test', v4],
['Deploy', v5],
]);
var options = {
title: 'Project Division',
trendlines: {
0: {type: 'linear', lineWidth: 5, opacity: .3},
1: { type: 'exponential', lineWidth: 10, opacity: .3 },
2: {type: 'curve', lineWidth: 10, opacity: .3}
},
hAxis: {
title: 'Time of Day'
},
vAxis: {
title: 'Rating (scale of 1-10)'
},
colors: ['#80ccff', '#85e085', '#ffb84d', '#b3b3ff', '#ffb3ff'],
backgroundColor: '#f1f2f7',
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
function add(name,val)
{
var data = new google.visualization.DataTable();
data.addColumn('string', 'Items');
data.addColumn('number', 'Sales');
data.addRows([
['Elicitation', v1],
['Design', v2],
['Code', v3],
['Test', v4],
['Deploy', v5],
[name, val]
]);
var options = {
title: 'Project Division',
trendlines: {
0: { type: 'linear', lineWidth: 5, opacity: .3 },
1: { type: 'exponential', lineWidth: 10, opacity: .3 },
2: { type: 'curve', lineWidth: 10, opacity: .3 }
},
hAxis: {
title: 'Time of Day'
},
vAxis: {
title: 'Rating (scale of 1-10)'
},
colors: ['#80ccff', '#85e085', '#ffb84d', '#b3b3ff', '#ffb3ff'],
backgroundColor: '#f1f2f7',
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
where I can add and remove data displayed in the bar chart. I tried multiple ways but none of them seem to work.
Finally what I was able to do was add one additional column using variable name and value. However, it is not practical to have preset constructors for lets say 1 additional column, 2 columns and so on. Furthermore this does not allow me to delete columns. What can I do to solve this?
While creating a stacked column chart using google charts, the annotations are getting overlapped due to large amount data. Is there anyway to get it adjusted. Like displaying only for every 3rd column. I know this concept works fine with highcharts but I was looking for free charts.
Annotation function call is :--
function drawVisualization() {
var json;
$.getJSON('end.json', function (json) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time');
data.addColumn('number', 'Run 3');
data.addColumn({ type: 'number', role: 'annotation' });
data.addColumn('number', 'Run 2');
data.addColumn({ type: 'number', role: 'annotation' });
data.addColumn('number', 'Run 1');
data.addColumn({ type: 'number', role: 'annotation' });
for (var i = 0; i< json[0].data.length; i++){
data.addRow([json[0].data[i], json[3].data[i],json[3].data[i],json[2].data[i],json[2].data[i],json[1].data[i], json[1].data[i]]);
}
var options = {
title: "End to End Processing",
tooltip: {isHtml: true},
legend:{position:"right"},
isStacked:true,
height:window.innerHeight,
width: window.innerWidth,
bar: {groupWidth: '3'},
focusTarget: 'category',
vAxis: {
viewWindowMode:'explicit',
viewWindow: {
max:60,
min:0
},
gridlines :{count:6},
title:'Time in mins',
format: 'short'
},
hAxis: {
format: 'd/m/y',
textStyle : {
fontSize: 9
},
slantedText: true,
slantedTextAngle: 270
},
annotations: {
textStyle: {
color: 'black',
fontSize: 11,
fontStyle: 'bold'
},
stemLength: 20,
displayAnnotationsFilter: true,
legendPosition: 'newRow'
},
series: {
0:{color:'lightgreen'},
1:{color:'black'},
2:{color:'#1E90FF',},
3:{ type: 'line', lineWidth: 0, visibleInLegend:false, pointSize: 0}
}
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
$(window).resize(function(){
drawVisualization();
});
}
Regards.
there isn't a standard option, but you can use null for blank annotations
when loading, try the following to show annotations for every third row...
for (var i = 0; i< json[0].data.length; i++){
var annotation1 = null;
var annotation2 = null;
var annotation3 = null;
if ((i % 3) === 0) {
var annotation3 = json[3].data[i];
var annotation2 = json[2].data[i];
var annotation1 = json[1].data[i];
}
data.addRow([
json[0].data[i],
json[3].data[i],
annotation3,
json[2].data[i],
annotation2,
json[1].data[i],
annotation1
]);
}
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>
I initially had a columnchart on page1 and a linechart on page2. They both display fine when on their own page. When I try combine the two on one page, they both display but they both are columncharts. I'm not sure what I am doing wrong. This is my code so far:
google.load('visualization', '1.0', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawchart);
function drawchart() {
var chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Arm');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < chartdatax.length; i++) {
chartData.addRow([parseFloat(chartdatax[i]),
parseFloat(chartdatay[i])]);
};
var options = {
height: 500,
hAxis: {
title: 'Arm C.G',
gridlines: {
count: 10
}
},
vAxis: {
title: 'Weight',
gridlines: {
count: 10
}
},
chartArea: {top:40, width: "70%", height: "75%"},
animation:{
duration: 1000,
easing: 'out',
startup: true,
},
legend: { position: 'none' },
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('chart1'));
myLineChart.draw(chartData, options);
}
function drawchart2(elevations, status) {
var chartDiv = document.getElementById('elevation_chart');
if (status !== google.maps.ElevationStatus.OK) {
// Show the error code inside the chartDiv.
chartDiv.innerHTML = 'Cannot show elevation: request failed because ' +
status;
return;
}
var chart = new google.visualization.ColumnChart(chartDiv);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation');
for (var i = 0; i < elevations.length; i++) {
data.addRow(['', elevations[i].elevation]);
}
chart.draw(data, {
height: 200,
legend: 'none',
titleY: 'Elevation (m)'
});
}
The code you have looks like it should work...
Would need to see where drawchart2 is called, the HTML elements, and any other code to be sure...
In this example, I add callback function drawcharts to start drawing...
google.load('visualization', '1.0', {'packages':['corechart'], 'callback': drawcharts});
function drawcharts() {
drawchart();
drawchart2();
}
function drawchart() {
var chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Arm');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < 10; i++) {
chartData.addRow([
parseFloat(i),
parseFloat(i * 1.5)
]);
};
var options = {
height: 500,
hAxis: {
title: 'Arm C.G',
gridlines: {
count: 10
}
},
vAxis: {
title: 'Weight',
gridlines: {
count: 10
}
},
chartArea: {top:40, width: "70%", height: "75%"},
animation:{
duration: 1000,
easing: 'out',
startup: true,
},
legend: {position: 'none'},
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('chart1'));
myLineChart.draw(chartData, options);
}
function drawchart2(elevations, status) {
var chartDiv = document.getElementById('elevation_chart');
var chart = new google.visualization.ColumnChart(chartDiv);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation');
for (var i = 0; i < 10; i++) {
data.addRow([
'',
i * 100
]);
}
chart.draw(data, {
height: 200,
legend: 'none',
titleY: 'Elevation (m)'
});
}
<script src="https://www.google.com/jsapi"></script>
<div id="chart1"></div>
<div id="elevation_chart"></div>