I'm trying to get "$" next to amount. Should look like: "$0.005"
How to do that?
PS. prefix: '$' doesn't work.
<script>
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Spent', 'Clicks'],
['US', 0.005, 1],
]);
var options = {
colorAxis: {
colors: ['grey','#444']
},
prefix: '$'
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
you can use object notation to provide both the value (v) and formatted value (f)...
{v: 0.005, f: '$0.005'}
see following working snippet...
google.charts.load('current', {
packages: ['geochart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Country', 'Spent', 'Clicks'],
['US', {v: 0.005, f: '$0.005'}, 1],
]);
var options = {
colorAxis: {
colors: ['grey','#444']
},
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="regions_div"></div>
or use a number formatter to format the data table (which does the same as above)...
var formatTooltip = new google.visualization.NumberFormat({
pattern: '$#,##0.000'
});
formatTooltip.format(data, 1);
see following working snippet...
google.charts.load('current', {
packages: ['geochart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Country', 'Spent', 'Clicks'],
['US', 0.005, 1],
]);
var options = {
colorAxis: {
colors: ['grey','#444']
},
};
var formatTooltip = new google.visualization.NumberFormat({
pattern: '$#,##0.000'
});
formatTooltip.format(data, 1);
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="regions_div"></div>
Related
Am a beginner using google charts/js. My google chart below loads fine, however there are times when the chart area loads blank html, and when I refresh the page it displays correctly.
I'm not sure why this is. It seems to do this on all browsers. This seems to indicate it could be with Mozilla, but the problem persists...
<script type="text/javascript">
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() {
<?php
$imei = $bboxx_imei;
$result = shell_exec('Daily_Data_Retriever_ishackweb.py ' . $imei.' '. $end.' '.$start); #imei=sys.arg[1] end=sys.arg[2] start=sys.arg[3]
?>
var jsonData = <?php echo $result; ?> //{"Charge Current, (A)":{"2017-11-16T00:00:00.000Z":0.001373312,"2017-11-16T00:01:00.000Z":0.001373312,"2017-11-16T00:02:00.000Z":0.001373312,"2017-11-16T00:03:00.000Z":0.001373312,"2017-11-16T00:04:00.000Z":0.001373312},"Battery Voltage, (V)":{"2017-11-16T00:00:00.000Z":12.9267109178,"2017-11-16T00:01:00.000Z":12.9267109178,"2017-11-16T00:02:00.000Z":12.9267109178,"2017-11-16T00:03:00.000Z":12.9267109178,"2017-11-16T00:04:00.000Z":12.9267109178}};
var chartCols = ['Datetime'];
Object.keys(jsonData).forEach(function (column) {
chartCols.push(column);
});
// build list of date
var dateValues = [];
Object.keys(jsonData).forEach(function (column) {
Object.keys(jsonData[column]).forEach(function (dateValue) {
if (dateValues.indexOf(dateValue) === -1) {
dateValues.push(dateValue);
}
});
});
// build chart data
var chartData = [chartCols];
dateValues.forEach(function (dateValue) {
var row = [new Date(dateValue)];
Object.keys(jsonData).forEach(function (column) {
row.push(jsonData[column][dateValue] || null);
});
chartData.push(row);
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'85%'},
//title: 'Battery Voltage and Panel Charge',
curveType: 'function',
legend: { position: 'bottom' },
vAxes: {0: {viewWindowMode:'explicit',
viewWindow:{
max:16,
min:11
},
gridlines: {color: 'transparent'},
},
1: {viewWindowMode:'explicit',
viewWindow:{
max:5,
min:0
},
},
},
series: {0: {targetAxisIndex:1},
1: {targetAxisIndex:0},
},
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
$(window).resize(function(){
drawChart()
});
});
</script>
when using a function inline / anonymously, although you can provide a name,
you will not be able to call that same function again, by it's name
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() { // <-- cannot call this again, no name needed
...
instead, declare the function separately, then pass a reference where needed,
using the name of the function
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
$(window).resize(drawChart);
function drawChart() {
...
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
$(window).resize(drawChart);
function drawChart() {
var jsonData = {"Charge Current, (A)":{"2017-11-16T00:00:00.000Z":0.001373312,"2017-11-16T00:01:00.000Z":0.001373312,"2017-11-16T00:02:00.000Z":0.001373312,"2017-11-16T00:03:00.000Z":0.001373312,"2017-11-16T00:04:00.000Z":0.001373312},"Battery Voltage, (V)":{"2017-11-16T00:00:00.000Z":12.9267109178,"2017-11-16T00:01:00.000Z":12.9267109178,"2017-11-16T00:02:00.000Z":12.9267109178,"2017-11-16T00:03:00.000Z":12.9267109178,"2017-11-16T00:04:00.000Z":12.9267109178}};
var chartCols = ['Datetime'];
Object.keys(jsonData).forEach(function (column) {
chartCols.push(column);
});
// build list of date
var dateValues = [];
Object.keys(jsonData).forEach(function (column) {
Object.keys(jsonData[column]).forEach(function (dateValue) {
if (dateValues.indexOf(dateValue) === -1) {
dateValues.push(dateValue);
}
});
});
// build chart data
var chartData = [chartCols];
dateValues.forEach(function (dateValue) {
var row = [new Date(dateValue)];
Object.keys(jsonData).forEach(function (column) {
row.push(jsonData[column][dateValue] || null);
});
chartData.push(row);
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'85%'},
//title: 'Battery Voltage and Panel Charge',
curveType: 'function',
legend: { position: 'bottom' },
vAxes: {
0: {
viewWindowMode:'explicit',
viewWindow:{
max:16,
min:11
},
gridlines: {color: 'transparent'},
},
1: {
viewWindowMode:'explicit',
viewWindow:{
max:5,
min:0
},
},
},
series: {
0: {targetAxisIndex:1},
1: {targetAxisIndex:0},
},
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
}
<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="line_chart"></div>
So, I have two Google bar charts displayed on the same page.I tried creating one event handler for both of them and passing in the chart and data into the selectHandler. Can someone tell me what I'm doing wrong?
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data1 = google.visualization.arrayToDataTable([
['Condition', 'Frequency'],
['Dementia', 6081],
['Hypertension', 6055],
['Hypercholesterolemia', 6035],
]);
var data2 = google.visualization.arrayToDataTable([
['Medication', 'Frequency'],
['Naproxen', 7632],
['Plavix', 7486]
]);
var options1 = {
title: 'Medical Conditions',
};
var options2 = {
title: 'Medications',
};
var conditionbarchart = new google.charts.Bar(
document.getElementById('conditions_chart'));
conditionbarchart.draw(data1, options1);
var medchart = new google.visualization.ColumnChart(
document.getElementById('medications_chart'));
medchart.draw(data2, options2);
google.visualization.events.addListener(conditionbarchart, 'select', selectHandler(conditionbarchart, data1));
google.visualization.events.addListener(medchart, 'select', selectHandler());
}
function selectHandler(mychart, mydata){
var selectedItem = mychart.getSelection()[0];
if(selectedItem){
var selection = mydata.getValue(selectedItem.row, 0);
alert('The user selected' + selection);
}
}
Here's the complete solution to answer my question:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.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', 'Condition');
data.addColumn('number', 'Frequency');
data.addRows([
['Dementia', 3],
['Hypertension', 1],
['Hypercholesterolemia', 1],
['Coronary artery disease', 1],
['Heaches', 2]
]);
// Create the data table.
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'Medication');
data2.addColumn('number', 'Frequency');
data2.addRows([
['Naproxen', 3],
['Plavix', 1],
['Lasix', 1],
['Insulin', 1],
['Neurontin', 2]
]);
// Set chart options
var options = {
bars: 'vertical', // Required for Material Bar Charts.
hAxis: {
slantedText:true,
slantedTextAngle:90
},
height: 400,
backgroundColor: {fill: 'transparent'},
legend: {position: 'none'},
colors: ['#1b9e77']
};
// Set chart options
var options2 = {
bars: 'vertical', // Required for Material Bar Charts.
hAxis: {
slantedText:true,
slantedTextAngle:90
},
height: 400,
backgroundColor: {fill: 'transparent'},
legend: {position: 'none'},
colors: ['#1b9e77']
};
// Instantiate and draw our chart, passing in some options.
var conditionsbarchart = new google.visualization.ColumnChart(document.getElementById('conditions_chart'));
var medchart = new google.visualization.ColumnChart(document.getElementById('medications_chart'));
function selectHandler(mychart, mydata) {
var selectedItem = mychart.getSelection()[0];
if (selectedItem) {
var topping = mydata.getValue(selectedItem.row, 0);
alert('The user selected ' + topping);
}
}
google.visualization.events.addListener(conditionsbarchart, 'select', function(){
selectHandler(conditionsbarchart, data);
});
conditionsbarchart.draw(data, options);
google.visualization.events.addListener(medchart, 'select', function(){
selectHandler(medchart, data2);
});
medchart.draw(data2, options2);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="conditions_chart" style="width:400; height:300"></div>
<div id="medications_chart" style="width: 400; height: 300"></div>
</body>
</html>
How to get the total number and percentage in google charts?
I just want to get the percent and the number in the google charts, are there options that need to be set?
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = google.visualization.arrayToDataTable([
['City', '2010 Population',],
['New York City, NY', 8175000],
['Los Angeles, CA', 3792000],
['Chicago, IL', 2695000],
['Houston, TX', 2099000],
['Philadelphia, PA', 1526000]
]);
var options = {
title: 'Population of Largest U.S. Cities',
chartArea: {width: '50%'},
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Sample output below:
use the group method to find the total
var groupData = google.visualization.data.group(
data,
[{column: 0, modifier: function () {return 'total'}, type:'string'}],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);
and a DataView to add an 'annotation' column
see following working snippet...
google.charts.load('current', {
callback: drawBasic,
packages: ['corechart']
});
function drawBasic() {
var data = google.visualization.arrayToDataTable([
['City', '2010 Population',],
['New York City, NY', 8175000],
['Los Angeles, CA', 3792000],
['Chicago, IL', 2695000],
['Houston, TX', 2099000],
['Philadelphia, PA', 1526000]
]);
var groupData = google.visualization.data.group(
data,
[{column: 0, modifier: function () {return 'total'}, type:'string'}],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);
var formatPercent = new google.visualization.NumberFormat({
pattern: '#,##0.0%'
});
var formatShort = new google.visualization.NumberFormat({
pattern: 'short'
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
var amount = formatShort.formatValue(dt.getValue(row, 1));
var percent = formatPercent.formatValue(dt.getValue(row, 1) / groupData.getValue(0, 1));
return amount + ' (' + percent + ')';
},
type: 'string',
role: 'annotation'
}]);
var options = {
annotations: {
alwaysOutside: true
},
title: 'Population of Largest U.S. Cities',
chartArea: {width: '50%'},
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I have a google scatter chart that has some significant thresholds in it. How do I visualise them?
Do I push some extra ticks on chart axis? If so how do I add just one and how do I style it?
I am aiming for something like this.
I am using React Google charts
add another column, or series, with the same value for all rows...
this can be added using a data view with calculated columns,
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['x', 'y0'],
[0, 165],
[1, 175],
[2, 185]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: function () {
return 150;
},
label: 'min',
type: 'number'
},
{
calc: function () {
return 175;
},
label: 'avg',
type: 'number'
},
{
calc: function () {
return 200;
},
label: 'max',
type: 'number'
}
]);
var options = {
vAxis: {
viewWindow: {
min: 125,
max: 225
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
EDIT
here's another example...
add additional columns to the data table,
use getColumnRange for find the min and max x-axis values
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['x', 'y0'],
[0, 165],
[1, 175],
[2, 185]
]);
var xAxisRange = data.getColumnRange(0);
data.addColumn({label: 'min', type: 'number'});
data.addColumn({label: 'avg', type: 'number'});
data.addColumn({label: 'max', type: 'number'});
data.addRows([
[xAxisRange.min, null, 150, 175, 200],
[xAxisRange.max, null, 150, 175, 200]
]);
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, {
series: {
1: {
color: 'cyan'
},
2: {
color: 'cyan'
},
3: {
color: 'cyan'
}
}
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
I have a CSV file with datetime timestamps (in milliseconds from 1970) as X axis separed tis a comma ',' and an associated Temperature value as Y axis.
ie :
1485097200000,22.5
1485098100000,23.8
1485099000000,24.2
etc ...
From that kind of CSV file i would like to generate a google graph code like this :
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
google.load('visualization', '1', {'packages':['annotatedtimeline']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Temperatures');
data.addRows([
[new Date(1485097200000), 22.5],
[new Date(1485098100000), 23.8],
[new Date(1485099000000), 24.2]
]);
var options = {
title: 'Temperature measured every 15 minutes',
width: 900,
height: 500,
hAxis: {
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: 'none'},
minValue: 0
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
var button = document.getElementById('change');
button.onclick = function () {
// If the format option matches, change it to the new option,
// if not, reset it to the original format.
options.hAxis.format === 'M/d/yy' ?
options.hAxis.format = 'MMM dd, yyyy' :
options.hAxis.format = 'M/d/yy';
chart.draw(data, options);
};
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button id="change">Click to change the format</button>
<div id="chart_div"></div>
Would you please tell if it is possible and how i could do it so , i'm newbie.
Regards,
Here is an example for how to get the get the data from a CSV file (in this case come from a string but the principal is the same.
The CSV file should look like this:
1486727700000,5\n1486728600000,7\n1486729200000,3\n1486729800000,1\n1486730400000,3\n1486731000000,4\n1486731600000,3\n1486732200000,4\n1486732800000,4
Also you need to extract the data from the file so here is the function.
function getData(csv) {
var output = [];
csv.split(/\n/).forEach(function(row) {
var cells = row.split(','),
date = new Date(parseInt(cells[0])),
value = parseFloat(cells[1]);
output.push([date, value]);
});
return output;
}
And live demo here:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// google.load('visualization', '1', {'packages':['annotatedtimeline']});
// google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Temperatures');
// data.addRows([
// [new Date(2017, 1, 10, 13, 55), 5], [new Date(2017, 1, 10, 14, 10), 7], [new Date(2017,1, 10,14,20), 3],
// [new Date(2017, 1, 10, 14, 30), 1], [new Date(2017, 1, 10, 14,40), 3], [new Date(2017, 1, 10, 14,50), 4],
// [new Date(2017, 1, 10,15,00), 3], [new Date(2017, 1, 10,15,10), 4], [new Date(2017, 1, 10,15,20), 2]
// ]);
data.addRows(getData(csvFile));
var options = {
title: 'Temperature measured every 15 minutes',
width: 900,
height: 500,
hAxis: {
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: 'none'},
minValue: 0
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
var button = document.getElementById('change');
button.onclick = function () {
// If the format option matches, change it to the new option,
// if not, reset it to the original format.
options.hAxis.format === 'M/d/yy' ? options.hAxis.format = 'MMM dd, yyyy' : options.hAxis.format = 'M/d/yy';
chart.draw(data, options);
};
}
var csvFile = '1486727700000,5\n1486728600000,7\n1486729200000,3\n1486729800000,1\n1486730400000,3\n1486731000000,4\n1486731600000,3\n1486732200000,4\n1486732800000,4';
function getData(csv) {
var output = [];
csv.split(/\n/).forEach(function(row) {
var cells = row.split(','),
date = new Date(parseInt(cells[0])),
value = parseFloat(cells[1]);
output.push([date, value]);
});
return output;
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button id="change">Click to change the format</button>
<div id="chart_div"></div>
http://output.jsbin.com/coxemay
Update
How to get the CSV from file using ajax
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(csvData) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Temperatures');
getData(function(csvData) {
data.addRows(csvData);
var options = {
title: 'Temperature measured every 15 minutes',
width: 900,
height: 500,
hAxis: {
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: 'none'},
minValue: 0
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
var button = document.getElementById('change');
button.onclick = function () {
// If the format option matches, change it to the new option,
// if not, reset it to the original format.
options.hAxis.format === 'M/d/yy' ? options.hAxis.format = 'MMM dd, yyyy' : options.hAxis.format = 'M/d/yy';
chart.draw(data, options);
};
}
function getData(callback) {
$.get('https://gist.githubusercontent.com/moshfeu/e3fd00cb57ae5b5cffbda44422dff112/raw/bcadcdfb5a532cc5711949a60cce639b2da235e6/csv-file', function(csv) {
var output = [];
csv.split(/\n/).forEach(function(row) {
var cells = row.split(','),
date = new Date(parseInt(cells[0])),
value = parseFloat(cells[1]);
output.push([date, value]);
});
callback(output);
});
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id="change">Click to change the format</button>
<div id="chart_div"></div>
http://jsbin.com/coxemay/3/edit?html,js,console