Google charts display Money not Percentages - javascript

Given the data for a pie chart:
data = new google.visualization.arrayToDataTable([
['Sales', 'Revenue Distribution'],
['Author', 5],
['Company', 2],
['Tax', 0.4],
['Payment Processors', 0.9]
]);
drawChart();
How can I make it display as dollar amounts? Either in the tooltip or on the actual graph itself (both would be preferable!)
For example, ideally this would work:
data = new google.visualization.arrayToDataTable([
['Sales', 'Revenue Distribution'],
['Author', '$5'],
['Company', '$2'],
['Tax', '$0.4'],
['Payment Processors', '$0.9']
]);
drawChart();

It is possible and it will apply it to both the slice and the tooltip. What you need to include is a number formatter.
The key things are to apply the following before you 'create' the chart.
var formatter = new google.visualization.NumberFormat({
prefix: '$'
});
formatter.format(data, 1);
var options = {
pieSliceText: 'value'
};
This first creates the formatter and applies it to the data, the next option then forces the pie chart to show the formatted value, rather than the calculated percentage. You can see it working in this jsfiddle.
Inspired and adapted by the answer here: Formatting google charts programmatically

Related

Retrieve value column header google visualisation

I want to retrieve the value of the column header when a user clicks on 1 of the bars of the chart. A report should be generated with the parameters I retrieve from the chart. This is what I have so far:
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.arrayToDataTable([
['Month', '2014', '2015'],
['Jan', 0, 200.00],
['Feb', 0, 400.00],
['Mar', 0, 700.00],
['Apr', 0, 100.00],
['May', 400.00, 900.00],
['Jun', 1100.00, 0],
['Jul', 3400.00, 0],
['Aug', 2500.00, 0],
['Sep', 2450.00, 0],
['Oct', 3170.00, 0],
['Nov', 2500.00, 0],
['Dec', 1979.00, 0]
]);
var options = {
title: 'Raised'
};
var chart = new google.charts.Bar(document.getElementById('chart_div_month'));
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var month = data.getValue(selectedItem.row, 0);
var year = data.getValue(0, selectedItem.column);
window.location = 'report.php?submit=Submit&year=' + year + '&month=' + month;
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}
I am able to retrieve the month parameter, but not the year.
Reading about google chart tables at their API page it says that
getSelection() - Standard getSelection implementation.
Selection elements are all row elements.
Can return more than one selected row.
So getSelection() doesn't select any column, and therefore var year = data.getValue(0, selectedItem.column);won't work.
Why it is like this I don't know, as the getSelection() returns both a row and a column, but the column is always null (thought it hasn't always been like this, there are loads of examples where people show how it works, but they are all broken today).
I have seen an approach that uses standard javascript (or was it jQuery?) to detect which column is clicked (clicked, not selected) by listening for mouseclicks on tds and getting the column property that way, but I can't seem to find it.

Show percentage in jqplot piechart tooltip

I'm using primefaces with jqplot library.
In my piechart i have the extender property and in the javascript function i have this:
this.cfg.highlighter = {
show:true,
tooltipLocation: 'n',
tooltipAxes: 'y',
useAxesFormatters: false,
tooltipFormatString: '%s'
}
The tooltip shows section value, but not section percentage.
Anybody knows how to show percentage value in tooltip?
Thanks.
You can bind the highlight event in order to modify the tooltip :
$("#chart1").bind('jqplotDataHighlight', function(ev, seriesIndex, pointIndex, data) {
var highlightToolTip = $(".jqplot-highlighter-tooltip");
var pct = Math.round(data[1]/total*100);
highlightToolTip.html(data[0]+", "+pct+"%");
});
Where :
data1 is the value of the highlighted slice,
data[0] is the label of the highlighted slice,
total is a variable containing the total value of your plot built here :
data = [
['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14],
['Out of home', 16],['Commuting', 7], ['Orientation', 9]
];
var total = 0;
$(data).map(function(){total += this[1];})
Please see a working example on
fiddle here

google bar/column chart set proper label width and chartarea width

i am using google chart to render charts, but sometimes the label is too long that the chart gets chopped, sometimes the chart is so long that the label gets cutting off, please check jsfiddle to see.
google.load('visualization', '1', {packages: ['corechart']});
var graphTitle = '', dataPoints = [];
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Option', 'Percent'],
['More than 75%', 47],
['50% to 74%', 36],
['30% to 49%', 10],
['10% to 29%', 4],
['Less than 10%', 3]
]);
$('body').data('quickpoll_179', data);
// Create and draw the visualization.
new google.visualization.BarChart(document.getElementById('quickpollChart')).
draw(data, {
title:'',
titleTextStyle: {color: '#000000'},
width:640, height:340,
legend: {position:'none'},
vAxis: {title: ""},
hAxis: {title: "",format:"#'%'"},
colors: ['#74317D'],
chartArea: {left:80.6,top:20, width:539.4,height:"340px"}
});
}
google.setOnLoadCallback(drawVisualization);
my question is how can i calc the proper width so if the chart is large, i can increase the whole container size and stop chart and lable being cutting off. i know for this case, i can increase the chart area, but it may not be applicable in every curcumstances. so it is better that i know how much space the google chart will take so i can dymaically resize the width and height of the container
I would say just decrease the size of the font, This is the default behaviour for a Google chart you cannot work with everything, what if the label was 1000 characters long. Then you would want the ellipse, you can still hover over the label to see the full text.
See updated fiddle: http://jsfiddle.net/9J4sS/1/
I achieved this by lowering the size of the text.
vAxis: {
title: "",
textStyle: {
fontSize:8
}
}
Or alternatively display your labels inside your graph using. http://jsfiddle.net/9J4sS/2/
vAxis: {
title: "",
textPosition: "in"
}

Organizing graph options in Google Charts

I'm creating a handful of pie charts using Google Charts. The majority of the graph options for the charts I'm creating are the same, except the titles. Is it possible to maintain a default set of options but write certain specific options for each graph (in this case, I just need to set a title).
Here's an example of the code I'm using:
var graphOptions = {
is3D: true,
pieSliceText: 'label',
colors: ['#F9B641', '#FBCB75', '#FCE1B0', '#FFF8EB', '#FFFFFF'],
backgroundColor: 'transparent',
titleTextStyle: {
color: '#FFF'
},
legend: {
textStyle: {
color: '#FFF'
}
},
chartArea: {
width: '90%',
height: '80%'
}
};
function pieChart1() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 216],
['Female', 238]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart1'));
chart.draw(data, graphOptions);
}
function pieChart2() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 116],
['Female', 98]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart2'));
chart.draw(data, graphOptions);
}
How would I go about setting the title option for each graph while still pulling the options from graphOptions?
As David explained, you can create an options object, and then edit properties of that object individually.
Here is a jsfiddle that shows it in action.
Note: you cannot see the titles because the BG and font color is white. Just do a ctrl+a to select everything and see them hidden there
Basically, you create a variable both functions can access (in your case graphOptions). In each function you set a new variable called options to equal graphOptions. You can then change the title property of the options variable to whatever you want without changing your default options template graphOptions, and use the options variable to draw the graph.
For your code, that means adding this code to each function:
var options = graphOptions;
options.title = "Pie Chart X"
You can change the title to whatever is appropriate, different for each graph. Then in the graph draw command, you change graphOptions to options to get
chart.draw(data, options);
Normally you'd do:
var options = { title: 'My Chat Title' };
In your case add title to your graphOptions object then do:
graphOptions.title = "The New Title";
for each graph.

get data from selected slice of google charts PieChart

i have big trouble trying to get the value of the selected slice of a PieChart when its clicked.
The documentation says:
selection_array: An array of selected objects, each one describing a
data element in the underlying table used to create the visualization
(a DataView or a DataTable). Each object has properties row and/or
column, with the index of the row and/or column of the selected item
in the underlying DataTable. If the row property is null, then the
selection is a column; if the column property is null, then the
selection is a row; if both are non-null, then it is a specific data
*item. You can call the DataTable.getValue()* method to get the value of
the selected item. The retrieved array can be passed into
setSelection()
in my case i get null from getSelection(), then i couldnt figure out what to do to get the value i want (the label of the column corresponding to that slice).
Any answer will be very apreciated :)
the example code of what im doing:
google.load('visualization', '1', {packages: ['controls']});
google.setOnLoadCallback(drawVisualization);
var data;
var pie_area;
function drawVisualization() {
// Prepare the data
data = google.visualization.arrayToDataTable([
["rbd", "nombre", "area", "dependencia", "simceMat", "ubicacionLon", "ubicacionLat", "simceLen", "nivel"],
[22616, "Colegio Mozart", "Urbana", "Part_Sub", 228, -72.981148, -41.479872, 254, "Basico"],
[22686,"Escuela Basica Camelias","Urbana","Muni",228,-72.980075,-41.474599,253, "Medio"],
[40351,"Colegio Bosquemar","Urbana","Part_Sub",290,-72.981148,-41.479872,280, "Medio"],
[7633,"Escuela Capitan Arturo Prat Chacon","Urbana","Muni",317,-72.909565,-41.474567,314, "Basico"],
[7659,"Escuela Rural Alerce","Rural","Muni",230,-72.91767,-41.399121,249, "Basico"],
[7671,"Escuela Rural Lagunitas","Rural","Muni",261,-72.964282,-41.459485,269, "Medio"],
[7690,"Escuela Rural Rio Blanco","Rural","Muni",217,-72.638597,-41.455786,229, "Medio"],
[7700,"Colegio San Francisco Javier","Urbana","Part",305,-72.942089,-41.470351,303, "Basico"],
[7717,"Instituto Aleman de Puerto Montt","Urbana","Part",321,-72.932482,-41.470001,310, "Medio"],
[7718,"The American School","Urbana","Part",317,-72.909,-41.456,314, "Medio"]
]);
var fltArea = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'f1',
'options': {
'filterColumnLabel': 'area',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
pie_area = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'chart2',
'options': {
'width': 300,
'height': 300,
'legend': 'none',
'title': 'Area',
'pieSliceText': 'label'
},
'view': {'columns': [2]}
});
new google.visualization.Dashboard(document.getElementById('dashboard')).bind([fltArea], [pie_area]).draw(data);
google.visualization.events.addListener(pie_area, 'select', onAreaSliceSelected);
}
function onAreaSliceSelected(){
var sel = pie_area.getChart().getSelection(); //is always null
console.log('you selected '+sel); //displays you selected null
}
The issue is in how your chart/data is set up.
You are currently aggregating all the data from column 2 to generate the chart. In this case you have 7 Urbana, and 3 Rural for your values, so it aggregates those 10 rows into two categories. Since each slice of the pie refers to a set of aggregate values, and pie charts only allow a single value to be selected, you can't get the selection of three rows that way.
Additionally, your category selector doesn't provide much use as it currently is, because if you select either Urbana or Rural, you end up getting a pie chart showing 100% of a single category.
If you set up your data differently, you will properly get an array of objects whenever you select a slice, as in this example:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
// Create and draw the visualization.
pieChart = new google.visualization.PieChart(document.getElementById('visualization'));
pieChart.draw(data, {title:"So, how was your day?"});
google.visualization.events.addListener(pieChart, 'select', onAreaSliceSelected);
}
function onAreaSliceSelected(){
var sel = pieChart.getSelection(); //is always null
alert('you selected '+sel); //displays you selected null
}

Categories

Resources