google visualization change label on all values on x-axis - google-visualization

I have a bunch of products which I use ColumnChart to show the product name on the x-axis and then two different values that the products have on my y-axis. Since there are a bunch of products it gets pretty messy if I show all of them at once on the ColumnChart therefore I use the ChartRangeFilter Control to be able to have a window of products.
Now my problem is that ChartRangeFilter can't use strings on the axises. But I don't want to display the product id on the x-axis, so is it possible to change the lable when it is displayd?
Hope you can understand what I mean. Below is some code to test in the google code playground
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['corechart', 'controls']});
</script>
<script type="text/javascript">
function drawVisualization() {
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard'));
var control = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'control',
'options': {
// Filter by the date axis.
'filterColumnIndex': 0,
'ui': {
'chartType': 'LineChart',
'chartOptions': {
'chartArea': {'width': '90%'},
'hAxis': {'baselineColor': 'none'}
},
'chartView': {
'columns': [0, 1, 2]
},
'minRangeSize': 1
}
},
// Initial range: 1 to 4.
'state': {'range': {'start': 1, 'end': 4}}
});
var chart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart',
'options': {
// Use the same chart area width as the control for axis alignment.
'chartArea': {'height': '80%', 'width': '90%'},
'hAxis': {'slantedText': false},
'vAxis': {'viewWindow': {'min': 0, 'max': 20}},
'legend': {'position': 'none'}
}
});
var data = new google.visualization.DataTable();
data.addColumn('number', 'Product ID');
data.addColumn('number', 'value1');
data.addColumn('number', 'valu2');
data.addRow([1, 11, 12]);
data.addRow([2, 15, 12]);
data.addRow([3, 10, 11]);
data.addRow([4, 11, 9]);
data.addRow([5, 8, 12]);
data.addRow([6, 4, 9]);
data.addRow([7, 8, 15]);
data.addRow([8, 8, 11]);
data.addRow([9, 8, 9]);
dashboard.bind(control, chart);
dashboard.draw(data);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body>
<div id="dashboard">
<div id="chart" style='width: 915px; height: 300px;'></div>
<div id="control" style='width: 915px; height: 50px;'></div>
</div>
</body>
</html>
Thanks in advance!

You can use a DataView to get around this problem. In the ControlWrapper, set the view.columns parameter like this:
var control = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'control',
'options': {
// Filter by the date axis.
'filterColumnIndex': 0,
'ui': {
'chartType': 'LineChart',
'chartOptions': {
'chartArea': {'width': '90%'},
'hAxis': {'baselineColor': 'none'}
},
'chartView': {
'columns': [0, 1, 2]
},
'minRangeSize': 1
}
},
// Initial range: 1 to 4.
'state': {'range': {'start': 1, 'end': 4}},
view: {
columns: [{
type: 'number',
calc: function (dt, row) {
return {v: row, f: dt.getFormattedValue(row, 0)};
}
}, 1, 2]
}
});
then reverse the process in the ChartWrapper's view.columns:
var chart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart',
'options': {
// Use the same chart area width as the control for axis alignment.
'chartArea': {'height': '80%', 'width': '90%'},
'hAxis': {'slantedText': false},
'vAxis': {'viewWindow': {'min': 0, 'max': 20}},
'legend': {'position': 'none'}
},
view: {
columns: [{
type: 'string',
label: data.getColumnLabel(0),
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
}
}, 1, 2]
}
});
That should get you what you want.
This code assumes you have a DataTable with 3 columns: a string (product name) and two number columns (value1 and value2). Here is a demo: http://jsfiddle.net/asgallant/55agF/

change the color of the text as of background
hAxis: {textStyle: {color: 'white'}},

Related

How to categoryFilter for a column that can't be displayed within Google Charts datatable

I am using Google Charts with a datatable build up like this:
'Created', 'Passed', 'Passed with Bugs','In
Process','Failed','Untested','Retest','Blocked','Functionality']
"August 31, 2020",1,10,3,5,23,0,0,"Functionality1"
"August 31, 2020",5,4,23,1,39,0,0,"Functionality2"
"August 31, 2020",1,10,3,5,23,0,0,"Functionality3"
"September 6, 2020",1,10,3,5,23,0,0,"Functionality1"
"September 6, 2020",5,4,23,1,39,0,0,"Functionality2"
I am grouping values by column 0 (date) and the visualization is done in a stacked Columnchart like this:
ColumnChart Example
Since I am mixing up numbers (columns 1-7) with a string (column 8) I create a DataView without column 8. If I don't do this I get the error "All series on a given axis must be of the same data type".
Still I would like to have column 8 to use it within a ControlWrapper as a "CategoryFilter".
E.g. draw the columnChar only showing "Functionality1" data.
Below my code. It is a mix of Jinja (running a Flask webserver) and javascript:
<body>
<script type="text/javascript">
var dataArrayTests = new Array();
</script>
{% for item in test_details %}
<script type="text/javascript">
dataArrayTests.push([
'{{ item["created"] }}',
parseInt('{{ item["Passed"] }}'),
parseInt('{{ item["Passed with bugs found"] }}'),
parseInt('{{ item["In Process"] }}'),
parseInt('{{ item["Failed"] }}'),
parseInt('{{ item["Untested"] }}'),
parseInt('{{ item["Retest"] }}'),
parseInt('{{ item["Blocked"] }}'),
'{{ functionality }}'
]);
</script>
{% endfor %}
<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawDashboard);
dataArrayTests.reverse()
dataArrayTests.unshift(['Created', 'Passed', 'Passed with Bugs','In Process','Failed','Untested','Retest','Blocked','Functionality'])
// Load the Visualization API and the controls package.
// Packages for all the other charts you need will be loaded
// automatically by the system.
google.charts.load('current', {'packages':['corechart', 'controls']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawDashboard);
function drawDashboard() {
// Everything is loaded. Assemble your dashboard...
var data = google.visualization.arrayToDataTable(dataArrayTests);
var result = google.visualization.data.group(
data,
[0],
[{'column': 1, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 2, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 3, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 4, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 5, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 6, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 7, 'aggregation': google.visualization.data.sum, 'type': 'number'}
]
)
var options = {
height: 600,
legend: { position: 'top' },
bar: { groupWidth: '75%' },
isStacked: true,
};
// Create a dashboard.
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
// Create a Category Filter, passing some options
var functionalityFilter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_div',
'options': {
//This gives an error right now since there is no column 8 in the view I create below. Index from 0-7 works without errors ... but these are not the columns I want to filter by
'filterColumnIndex' : 8
}
});
// Create a ColumnChart, passing some options
var columnStack = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart_div',
'options': {
"height": 600,
"legend": { position: 'top' },
"bar": { groupWidth: '75%' },
"isStacked": true,
}
});
// Create a view to filter out column 8 to avoid the error "All series on a given axis must be of the same data type"
var view = new google.visualization.DataView(result)
view.setColumns([0,1,2,3,4,5,6,7]);
dashboard.bind(functionalityFilter, columnStack)
dashboard.draw(view);
}
</script>
Found the mistake(s).
When pushing to "dataArrayTests" I had a typo in the last column. {{ functionality }} should have been {{ item['functionality']}} . So the column I wanted to filter on was never filled with data and could not function.
Within the dataArray I now define the "functionality" (column 8) with the role "tooltip". That way it does not get considered for the x-axis, but I can still use to to filter.
Adjusted code below:
<script type="text/javascript">
var dataArrayTests = new Array();
</script>
{% for item in test_details %}
<script type="text/javascript">
dataArrayTests.push([
'{{ item["created"] }}',
parseInt('{{ item["Passed"] }}'),
parseInt('{{ item["Passed with bugs found"] }}'),
parseInt('{{ item["In Process"] }}'),
parseInt('{{ item["Failed"] }}'),
parseInt('{{ item["Untested"] }}'),
parseInt('{{ item["Retest"] }}'),
parseInt('{{ item["Blocked"] }}'),
'{{ item["functionality"] }}'
]);
</script>
{% endfor %}
<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawDashboard);
dataArrayTests.reverse()
dataArrayTests.unshift(['Created', 'Passed', 'Passed with Bugs','In Process','Failed','Untested','Retest','Blocked',{type: 'string', role: 'tooltip'}])
// Load the Visualization API and the controls package.
// Packages for all the other charts you need will be loaded
// automatically by the system.
google.charts.load('current', {'packages':['corechart', 'controls']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawDashboard);
function drawDashboard() {
// Everything is loaded. Assemble your dashboard...
console.log(dataArrayTests)
var data = google.visualization.arrayToDataTable(dataArrayTests);
var result = google.visualization.data.group(
data,
[0],
[{'column': 1, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 2, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 3, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 4, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 5, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 6, 'aggregation': google.visualization.data.sum, 'type': 'number'},
{'column': 7, 'aggregation': google.visualization.data.sum, 'type': 'number'},
])
result.sort([{column: 0}])
var options = {
height: 600,
legend: { position: 'top' },
bar: { groupWidth: '75%' },
isStacked: true,
};
// Create a dashboard.
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
// Create a Category Filter, passing some options
var functionalityFilter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_div',
'options': {
'filterColumnIndex' : 8
}
});
// Create a ColumnChart, passing some options
var columnStack = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart_div',
'options': {
"height": 600,
"legend": { position: 'top' },
"bar": { groupWidth: '75%' },
"isStacked": true
}
});
dashboard.bind(functionalityFilter, columnStack)
dashboard.draw(data);
}
</script>

How to Query multiple spreadsheets and make charts on same page

I am trying to develop a small web app which query the multiple google spreadsheets and make the graphs on the same page. I can query the single spreadsheet and chart the matching data like this and it is working fine.
<html>
<head>
<title>
Test
</title>
<script src="http://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load('visualization', '1', {'packages': ['table', 'controls', 'corechart']});
google.setOnLoadCallback(initialize);
function initialize() {
var urlMonth = 'https://docs.google.com/spreadsheets/d/1y5MgFR67kn1-GHbmeIi6wuC5hmP10x4O8vAs5RWD8Sw/edit#gid=0'
var queryStringMonthly = encodeURIComponent("select A, B, C, D, E, F, G, H, I GROUP BY A LABEL A 'Gene' ");
var queryMonthCurrent = new google.visualization.Query(urlMonth+
queryStringMonthly);
queryMonthCurrent.send(megaData);
}
function megaData(monthData) {
var monthData_table = monthData.getDataTable(firstRowIsHeader = true);
var monthData_tablePivot = new google.visualization.DataTable();
monthData_tablePivot.addColumn('string');
monthData_tablePivot.addColumn('number');
monthData_tablePivot.addColumn({type: 'string', label: 'Gene', role: 'annotation'});
var newRows = []; //
//iterate through each row
for (i = 0; i < monthData_table.getNumberOfRows(); i ++) {
var issue = monthData_table.getValue(i, 0);
//iterate through each column
for (j = 1; j < monthData_table.getNumberOfColumns(); j ++ ){
var newRow = [];
rep = monthData_table.getColumnLabel(j);
newRow.push(rep);
newRow.push(monthData_table.getValue(i, j));
newRow.push(issue);
newRows.push(newRow); //push each newRow to newRows
}
}
monthData_tablePivot.addRows( newRows);
// Create a dashboard.
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div4'));
// Create filter
var issueFilter = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'filter_div4',
'options': {
'filterColumnLabel': 'Gene',
'ui': {
'allowMultiple': false,
'allowNone': false,
}
},
//Set default filter value
'state': {'selectedValues': [monthData_table.getValue(0 , 1)]}
}
);
//create chart
var yearChart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'current_year',
'options': {
'legend': 'none',
'width': 1100,
'height': 500,
hAxis: {
textStyle: {
color: 'black', // any HTML string color ('red', '#cc00cc')
fontName: 'Times New Roman', // i.e. 'Times New Roman'
fontSize: 12, // 12, 18 whatever you want (don't specify px)
bold: true, // true or false
italic: false // true of false
},
'title': 'Gene', titleTextStyle:{color:'black',fontSize: 16,bold:
true,italic: false}
},
vAxis: {title: 'Expression', titleTextStyle:{color:'black',fontSize:
16,bold: true,italic: false},
textStyle: {
color: 'black', // any HTML string color ('red', '#cc00cc')
fontName: 'Times New Roman', // i.e. 'Times New Roman'
fontSize: 12, // 12, 18 whatever you want (don't specify px)
bold: true, // true or false
italic: false // true of false
}
},
//Set the fontsize of labels so they don't show up crazily
'annotations': {'textStyle': {'opacity': 0},
//use 'line' style so to remove the line
pointer
'style': 'point',
'stemLength': 0
},
}
});
// bind charts and controls to dashboard
dashboard.bind(issueFilter, yearChart);
// Draw the dashboard.
dashboard.draw(monthData_tablePivot);
}
</script>
<style>
.SearchBar input {
height: 30px;
width: 400px;
}
</style>
</head>
<body>
<!--Div that will hold the dashboard-->
<center>
<h2>Seach gene expression</h2>
<div id="dashboard_div4" class="SearchBar" placeholder="Search">
<div id="filter_div4" > </div></center>
<div id="current_year" style="width:1100px; height: 300px;">
</div>
</div>
</html>
This repository is very close to my need but I don't know how to query the multiple spreadsheet. My another spreadsheet look like this
https://docs.google.com/spreadsheets/d/1vmPmaL78N-Ywz7s1y_VRSvQAZxjacN4mo7uKKrWrwzE/edit#gid=0

Multiple Google charts on one web page

I've 2 google charts on one page and both are displayed correctly. The problem is when I set fontName of both charts to 'Open Sans', only one chart is displayed. If both charts have some other font like 'Arial', then both are displayed. Also, if fontName for one chart is 'Open Sans' and 'Arial' for other, both charts are displayed. Error is only with 'Open Sans' for both charts. I've included Below is my code snippet. Can't get a solution to this. Please help. Thanks in advance..!!
<script type="text/javascript">
function commodityChart(){
// Load the Visualization API and the piechart package.
google.load('visualization', '1.1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
for($i=0;$i<count($data);$i++){
if($data[$i]->SEGMENT == 'COMMODITY'){
echo "['" . $data[$i]->PARAMETER . "'," . $data[$i]->AMOUNT . "],";
}
}
?>
]);
var formatter = new google.visualization.NumberFormat({prefix: '₹', format:'##,##,###.00'} );
formatter.format(data, 1);
// Set chart options
var options = {pieHole: 0.4,
fontSize: 13,
fontName: 'Open Sans',
is3D : true,
pieSliceText: 'value',
sliceVisibilityThreshold: 0,
// pieStartAngle: 100,
slices: {0: {offset: 0.3}},
//fontName: 'Open Sans',
legend: {position: 'right', alignment:'end'},
colors: ['#9bc53d', '#FF9900'],
'width':600,
// chartArea:{left:30,top:20,width:'70%',height:'75%'},
'height':500};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('gchart_pie_2'));
chart.draw(data, options);
}
}
</script>
<script type="text/javascript">
function equityChart(){
// Load the Visualization API and the piechart package.
google.load('visualization', '1.1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart1);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart1() {
// Create the data table.
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'type');
data1.addColumn('number', 'amount');
//data.addColumn({type: 'string', role: 'tooltip'});
data1.addRows([
<?
for($i=0;$i<count($data);$i++){
if($data[$i]->SEGMENT == 'EQUITY'){
echo "['" . $data[$i]->PARAMETER . "'," . $data[$i]->AMOUNT . "],";
}
}
?>
]);
var formatter = new google.visualization.NumberFormat({prefix: '₹', format:'##,##,###.00'} );
formatter.format(data1, 1);
// Set chart options
var options1 = {pieHole: 0.4,
is3D: true,`enter code here`
legend: {position: 'right', alignment:'end'},
//fontSize: 13,
fontName: 'Open Sans',
forceIFrame: false,
// pieSliceBorderColor: 'red',
pieSliceText: 'value',
//pieSliceTextStyle: {fontName: 'Open Sans', fontSize: 13},
chartArea:{left:20,top:20,width:'70%',height:'75%'},
// pieStartAngle: 20,
// slices: {0: {offset: 0.4}},
sliceVisibilityThreshold: 0,
// colors: ['#5bc0eb','#fde74c', '#9bc53d', '#e55934', '#fa7921'],
colors: ['#9bc53d','#fde74c', '#e55934', '#5bc0eb', '#FF9900'],
//tooltip: {isHtml: true},
'width':600,
'height':500};
// Instantiate and draw our chart, passing in some options.
var chart1 = new google.visualization.PieChart(document.getElementById('gchart_pie_1'));
chart1.draw(data1, options1);
}
}
enter code here
Try drawings the charts one at a time, that seems to fix the problem...
Here, I use the ready event to wait for the first chart to draw, then draw the second.
google.load('visualization', '1.1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
commodityChart();
}
function commodityChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Pepperoni', 33],
['Hawaiian', 26],
['Mushroom', 22],
['Sausage', 10],
['Anchovies', 9]
]);
var options = {
pieHole: 0.4,
fontSize: 13,
fontName: 'Open Sans',
is3D: true,
pieSliceText: 'value',
sliceVisibilityThreshold: 0,
slices: {
0: {
offset: 0.3
}
},
legend: {
position: 'right',
alignment:'end'
},
colors: [
'#9bc53d',
'#FF9900'
],
width: 600,
height: 500
};
var chart = new google.visualization.PieChart(document.getElementById('gchart_pie_2'));
google.visualization.events.addListener(chart, 'ready', equityChart);
chart.draw(data, options);
}
function equityChart() {
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'type');
data1.addColumn('number', 'amount');
data1.addRows([
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options1 = {
pieHole: 0.4,
is3D: true,
legend: {
position: 'right',
alignment: 'end'
},
fontName: 'Open Sans',
forceIFrame: false,
pieSliceText: 'value',
chartArea: {
left: 20,
top: 20,
width: '70%',
height: '75%'
},
sliceVisibilityThreshold: 0,
colors: [
'#9bc53d',
'#fde74c',
'#e55934',
'#5bc0eb',
'#FF9900'
],
width: 600,
height: 500
};
var chart1 = new google.visualization.PieChart(document.getElementById('gchart_pie_1'));
chart1.draw(data1, options1);
}
<script src="https://www.google.com/jsapi"></script>
<div id="gchart_pie_1"></div>
<div id="gchart_pie_2"></div>

Google Line Charts, place circle on annotation

i am new to google charts i want to make a graph for cricket rate rate and wicket that should look something like this
i have searched google and found out that i might do it with the help of annotations and i have written this code:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Overs');
data.addColumn('number', 'Run-rate');
data.addColumn({type: 'string', role:'annotation'});
data.addColumn({type: 'string', role:'annotationText'});
data.addRows([
[1, 6, null, null],
[2, 6, null, null],
[10, 2, null, null],
[20, 3.2, null, 'Shoaib Malik'],
[21, 3, '2', 'Shahid Afridi'],
[30, 4, null, null],
[40, 5, 'B', 'This is Point B'],
[50, 6, null, null],
]);
var options = {
title: 'Run Rate',
pointSize:0,
hAxis: {
gridlines: {
color: 'transparent'
}
},
};
new google.visualization.LineChart(document.getElementById('chart_div')).
draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
and this is the output of the code:
now the problem is that i want to show circle like the first image instead of text 2,B
i cant do it using pointSize because i want circle where wicket falls, not where the over ends...
can any1 tell me how to do this ? either i can replace text with circle or any other way out
You can't replace the text if you want to use the annotation functionality (as the text is what is generated by the annotations). You could use an overlapping data series to show only certain points. Here's an example that shows an overlapping series (I removed the annotations for simplicity, but you can still use them if you want to):
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Overs');
data.addColumn('number', 'Run-rate');
data.addColumn('boolean', 'Wicket falls');
data.addRows([
[1, 6, false],
[2, 6, false],
[10, 2, true],
[20, 3.2, false],
[21, 3, true],
[30, 4, true],
[40, 5, false],
[50, 6, false]
]);
// create a DataView that duplicates points on the "Run Rate" series where "Wicket falls" is true
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'number',
label: data.getColumnLabel(2),
calc: function (dt, row) {
// return the value in column 1 when column 2 is true
return (dt.getValue(row, 2)) ? dt.getValue(row, 1) : null;
}
}]);
var options = {
title: 'Run Rate',
pointSize:0,
hAxis: {
gridlines: {
color: 'transparent'
}
},
series: {
0: {
// put any options pertaining to series 0 ("Run-rate") here
},
1: {
// put any options pertaining to series 1 ("Wicket Falls") here
pointSize: 6,
lineWidth: 0
}
}
};
new google.visualization.LineChart(document.getElementById('chart_div')).
// use the view instead of the DataTable to draw the chart
draw(view, options);
}
google.load('visualization', '1', {packages:['corechart'], callback: drawVisualization});
See working example here: http://jsfiddle.net/asgallant/saTWj/

How to change color of annotation text in google-charts

How do you change the color of an annotation text in Google Chart Tools LineChart ?
Here is an example
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Sales');
data.addColumn({id: 'title', label: 'Title', type: 'string', role: 'annotation'});
data.addRows([
[new Date(2012, 3, 5), 80, null],
[new Date(2012, 3, 12), 120, 'New Product'],
[new Date(2012, 3, 19), 80, null],
[new Date(2012, 3, 26), 65, null],
[new Date(2012, 4, 2), 70, null],
]);
var options = {
title: 'Sales by Week',
displayAnnotations: true,
hAxis: {title: 'Date',
titleTextStyle: {color: 'grey'}},
colors: ['#f07f09']
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I want the line to be orange and the annotation text in grey. Currently the annotation text is orange.
No need for extra style data column and plumbing code to fill it for every row with ugly (and even incomplete above) formatting string. Only resort to separate styling column if you want to have different annotation color for the different data points.
There's a global setting, search for annotations.textStyle in https://developers.google.com/chart/interactive/docs/gallery/linechart
var options = {
annotations: {
textStyle: {
fontName: 'Times-Roman',
fontSize: 18,
bold: true,
italic: true,
// The color of the text.
color: '#871b47',
// The color of the text outline.
auraColor: '#d799ae',
// The transparency of the text.
opacity: 0.8
}
}
};
Here is a concept code for your case (notice different initialization google.charts, very important):
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
google.charts.load('current', { 'packages': ['corechart', 'line', 'bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Sales');
data.addColumn({id: 'title', label: 'Title', type: 'string', role: 'annotation'});
data.addRows([
[new Date(2012, 3, 5), 80, null],
[new Date(2012, 3, 12), 120, 'New Product'],
[new Date(2012, 3, 19), 80, null],
[new Date(2012, 3, 26), 65, null],
[new Date(2012, 4, 2), 70, null],
]);
var options = {
chart: {
title: 'Sales by Week'
},
hAxis: {
title: 'Date',
titleTextStyle: {color: 'grey'}
},
annotations: {
textStyle: {
color: 'grey',
}
}
colors: ['#f07f09']
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
You can also change other text formatting of the annotation, like bold, italic, font type, etc. Here is an example where most of the text is configured to be bold:
var options = {
chart: {
title: title
},
hAxis: {
textStyle: {
bold: true
}
},
vAxis: {
format: 'decimal',
textStyle: {
bold: true
}
},
legendTextStyle: {
bold: true
},
titleTextStyle: {
bold: true
},
width: chart_width,
//theme: 'material', // material theme decreases the color contrast and sets the black color items (all text) to 171,171,171 grey -> washed out
annotations: {
alwaysOutside: true,
highContrast: true, // default is true, but be sure
textStyle: {
bold: true
}
}
};
More examples with source repo link: https://mrcsabatoth.github.io/GoogleChartsTalk/
Actually you can. Color of the annotations is the same as line color. Just put a dot in the place you want to make an annotation and set a dot's color to the desirable annotation color.
data.addColumn({type: 'string', role: 'style'});
data.addColumn({type:'string', role:'annotation'});
and then when you add data
'point { size: 14; shape-type: circle; fill-color: #63A74A','Your annotation'
See example at
http://www.marketvolume.com/stocks/stochasticsmomentumindex.asp?s=SPY&t=spdr-s-p-500
If your annotations are not "touching", ie. the points you'd like to annotate are not next to each other, you could add a second line and add the annotations to that line.
In the JSON example below I have a date and a "total balance", as well as an "Ann" line.
"cols":[
{
"id":"date",
"label":"date",
"type":"date",
"p":{
"role":"domain"
}
},
{
"id":"total-balance",
"label":"Total balance",
"type":"number",
"p":{
"role":"data"
}
},
{
"id":"ann",
"label":"Ann",
"type":"number",
"p":{
"role":"data"
}
},
{
"type":"string",
"p":{
"role":"annotation"
}
},
{
"type":"string",
"p":{
"role":"annotationText"
}
}
],
The annotation comes after the "Ann" column so it'll be added to the "Ann" data points.
In my JSON, the date and "total-balance" are always filled in. "Ann" and the annotations are usually empty:
"rows":[
{
"c":[
{
"v":"Date(2013, 0, 1)"
},
{
"v":1000
},
{
"v":null
},
{
"v":null
},
{
"v":null
}
]
},
{
"c":[
{
"v":"Date(2013, 0, 8)"
},
{
"v":1001
},
{
"v":null
},
{
"v":null
},
{
"v":null
}
]
},
When I need an annotation, the "Ann" cell gets the same value as the total balance, and the annotation is added:
{
"c":[
{
"v":"Date(2013, 1, 26)"
},
{
"v":2000
},
{
"v":2000
},
{
"v":"Something!"
},
{
"v":"Something happened here!"
}
]
},
In your GChart's configuration, you can now set two colours. One for the normal line, and one for the "Ann".
colors: ['black','red']
If you have no annotations "touching", GCharts will not draw a line between them and the points will remain "invisible", while the annotations show up at exactly the right place.
Short answer: no, you can't change the text color through standard options (you could write something to find that text in the SVG and change its color with javascript, but that is beyond my level).
You can see an answer from ASGallant on Google Groups here, and his example here.
// code borrowed from Google visualization API playground, slightly modified here
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'x');
data.addColumn({type: 'string', role: 'annotation'});
data.addColumn({type: 'string', role: 'annotationText'});
data.addColumn('number', 'Cats');
data.addColumn('number', 'Blanket 1');
data.addColumn('number', 'Blanket 2');
data.addRow(["A", null, null, 1, 1, 0.5]);
data.addRow(["B", null, null, 2, 0.5, 1]);
data.addRow(["C", null, null, 4, 1, 0.5]);
data.addRow(["D", null, null, 8, 0.5, 1]);
data.addRow(["E", 'foo', 'foo text', 7, 1, 0.5]);
data.addRow(["F", null, null, 7, 0.5, 1]);
data.addRow(["G", null, null, 8, 1, 0.5]);
data.addRow(["H", null, null, 4, 0.5, 1]);
data.addRow(["I", null, null, 2, 1, 0.5]);
data.addRow(["J", null, null, 3.5, 0.5, 1]);
data.addRow(["K", null, null, 3, 1, 0.5]);
data.addRow(["L", null, null, 3.5, 0.5, 1]);
data.addRow(["M", null, null, 1, 1, 0.5]);
data.addRow(["N", null, null, 1, 0.5, 1]);
// Create and draw the visualization.
var chart = new google.visualization.LineChart(document.getElementById('visualization'));
chart.draw(data, {
annotation: {
1: {
style: 'line'
}
},
curveType: "function",
width: 500,
height: 400,
vAxis: {
maxValue: 10
}
});
}
The best you can do is to change the style of the line, but it doesn't look like you can currently change the color of the line.
Has this been updated using the 'style' option where one could add a new column {"type":"string","role":"style"} and in each row we would have {"v":"point {size: 4; fill-color: #3366cc;}"}? This allows the annotation to have the same color as the point/marker (which could be changed for each point) but does not allow it to be bold. One example of the data to try would be,
var data =new google.visualization.DataTable(
{
"cols":[
{"label":"Log GDP Per-Capita ","type":"number"},
{"label":"New Chart",
"type":"number"},
{"type":"string","role":"annotation"},
{"type":"string","role":"style"}
],
"rows":[
{"c":[{"v":10.21932},{"v":12.3199676},{"v":"ABW"},{"v":"point {size: 4; fill-color: #3366cc;}"}]},
{"c":[{"v":10.68416},{"v":8.4347518},{"v":"ARE"},{"v":"point {size: 4; fill-color: #3366cc;}"}]},
{"c":[{"v":9.634226},{"v":12.0774068},{"v":"ATG"},{"v":"point {size: 4; fill-color: #3366cc;}"}]},
{"c":[{"v":10.83869},{"v":1.8545959},{"v":"AUS"},{"v":"point {size: 4; fill-color: #3366cc;}"}]},
{"c":[{"v":10.7687},{"v":7.4919999},{"v":"AUT"},{"v":"point {size: 4; fill-color: #3366cc;}"}]}
]
}
);