Google Pie Chart pointing line between legend and pie chart - javascript

I would like to add a line to connect the pie chart to the label so the user can see what is the legend for the particular part of pie chart.
these are the codes i use to generate my piechart
function drawVisualizationIamIn(dataValues) {
console.log(dataValues)
var data = new google.visualization.DataTable();
data.addColumn('string', 'Column Name');
data.addColumn('number', 'Column Value');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
}
new google.visualization.PieChart(
document.getElementById('visualizationIamIn')
).draw(data, {
title: "Members by Industry Type",
sliceVisibilityThreshold: 0,
backgroundColor: '#e0e7eb'
});
}
Any help is appreciated, thank you.
below is the chart i generate with codes above.

use the following option...
{
legend: {
position: 'labeled'
}
}

Related

Why would I have to do chart.draw twice to get a Google pie chart to display?

I have a page in an app that displays all sorts of ticket metrics from several different ticketing systems we use. I use the same function to build each of the charts and display them:
function drawChart(chartData, chartStyle, chartTitle, chartSpanID) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Hour');
data.addColumn('number', 'Tickets');
data.addRows(chartData);
if(chartStyle == "column"){
var chart = new google.visualization.ColumnChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,chartArea: {left: 30, top:20, bottom:30, right:10},animation:{startup: true, duration:2000}}
};
if(chartStyle == "pie"){
var chart = new google.visualization.PieChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,
chartArea:{left: 0, top:20, bottom:10, right: 0},
is3D: true,
sliceVisibilityThreshold: .01,
animation:{startup: true,easing: 'in', duration:1000},
pieResidueSliceLabel: "Other( < 1%)"};
};
chart.draw(data, options);
}
This works for 13 of the 14 charts displayed on the page. 8 Columns and 5 out of 6 pie charts all display perfectly. One of the pie charts will ONLY display if I draw the chart a second time.
function drawChart(chartData, chartStyle, chartTitle, chartSpanID) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Hour');
data.addColumn('number', 'Tickets');
data.addRows(chartData);
if(chartStyle == "column"){
var chart = new google.visualization.ColumnChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,chartArea: {left: 30, top:20, bottom:30, right:10},animation:{startup: true, duration:2000}}
};
if(chartStyle == "pie"){
var chart = new google.visualization.PieChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,
chartArea:{left: 0, top:20, bottom:10, right: 0},
is3D: true,
sliceVisibilityThreshold: .01,
animation:{startup: true,easing: 'in', duration:1000},
pieResidueSliceLabel: "Other( < 1%)"};
};
chart.draw(data, options);
chart.draw(data, options);
}
The data is delivered correctly, all calls are made through google.charts.setOnLoadCallback, it all works just fine once called again... so why is it only working on the second call? Why just the one chart that doesn't display as expected? What have I missed?

Loop data in a Google chart

I want to create a loop, in my google chart, i have 200 points in the chart, and it moves 1 point to the right per second,but i want to repeat the chart when it reach all points.
here is my code of the chart:
function drawChart5() {
var options = {
'backgroundColor': 'transparent',
width: 1200,
height: 240,
animation: {
duration: 1000,
easing: 'in',
},
hAxis: {viewWindow: {min:0, max:200}}
};
var chart = new google.visualization.AreaChart(
document.getElementById('visualization'));
var data = new google.visualization.DataTable();
data.addColumn('string', 'x');
data.addColumn('number', 'y');
var MAX = 100;
var x=0;
var f=20;
var T= 1/f;
var PI = Math.PI;
var DT=T/MAX;
for (var i = 0; i < 2*MAX; i++)
{
x=(Math.sin((2*PI)*f*i*DT));
data.addRow([i.toString(), x]);
console.log(x)
}
function drawChart() {
google.visualization.events.addListener(chart, 'ready',
function() {
});
chart.draw(data, options);
}
setInterval(function()
{
options.hAxis.viewWindow.min += 1;
options.hAxis.viewWindow.max += 1;
chart.draw(data,options)
},2 000);
drawChart();
}
This is the chart
I would achieve the effect you are going for like this:
Use a DataView instead of a DataTable, and use DataView.setColumns() to create a calculated column that runs the formula defined above. As far as I can tell, the algorithm you use to calculate your values is deterministic, so all you need to run your calculations is the x-value and you can determine the y-value for any given position.
With this method, you'll never have to populate a DataTable yourself, because the chart uses your function to calculate the y-value on demand. Whatever range your chart displays, it will calculate the values it needs when the chart is drawn.

How to plot indicator circle onto google charts line chart

Google charts' line chart
So, at the moment, I'm just getting used to google charts. But in future, I'm looking to plot a function. Once that line is drawn, I'd like to add a dynamic indicator circle that will travel along the path of the line as I adjust the values that plotted the line.
So to summarise:
Plot a permanent line from a function*
Have a circle that travels the path of the line as I adjust the values of the function. (main question)
New to google charts and not sure how easily you can do something like this.
To maybe clarify: I will be using a slider to control a value, as I move the slider the line will not change, but an "indicator" circle will change position to fit the new values; i.e. plotting a circle dynamically as the value changes.
Not sure if it helps, but my current graph looks simply like this:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
drawChart();
function drawChart() {
var data = google.visualization.arrayToDataTable([
['somVar1', 'someVar2'],
['0.001' , 0.02],
['0.003' , 0.07],
['0.01' , 0.2],
['0.03' , 0.6 ],
['0.1' , 1.8],
['0.3' , 4.8],
['1' , 10],
['3' , 15.2 ],
['10' , 18.2 ],
['30' , 19.4],
['100' , 19.8],
['300' , 19.93],
['1000' , 19.98],
]);
//Graph styling and legend
var options = {
title: 'sumVar2 (%)',
curveType: 'function',
legend: { position: 'bottom' },
vAxis: { title: 'someVar2 %'},
hAxis: { title: 'someVar1'}
};
var chart = new google.visualization.LineChart(document.getElementById('lineGraph'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="lineGraph" style="width: 900px; height: 500px"></div>
*(unfortunately with google charts, it looks like I have to do this by finding the range of values and spitting them out into an array - rather than being able to plot straight from a mathematical function)
the DataView Class can be used to provide a function as the value for a series
use the setColumns method to set the function
you can pass a column index for an existing DataTable column or
a custom object with the calculation function
here, a DataView is created from a DataTable,
it uses the first column from the DataTable,
the next column is a function
var dataView = new google.visualization.DataView(dataTable);
dataView.setColumns([0, {
calc: function (data, row) {
return (2 * data.getValue(row, 0)) + 7;
},
type: 'number',
label: 'Y1'
}]);
you can set multiple column functions,
but you cannot use the values from one function in another,
in the same DataView
to get around, reference the previous DataView in the current function
otherwise, you would have to dump the values to a new table,
then use the new table in another view to set the next function
you can modify the series options to create points rather than a line, i.e.
series: {
1: {
lineWidth: 0,
pointSize: 8
}
}
the following working snippet demonstrates how to save a reference to the first function, and use it later, such as when the chart's 'ready' event fires
google.charts.load('current', {
callback: function () {
// DataTable X only
var dataTable = google.visualization.arrayToDataTable([
['X'],
[0.001],
[0.003],
[0.01],
[0.03],
[0.1],
[0.3],
[1],
[3],
[10],
[30],
[100],
[300],
[1000],
]);
// use DataView to provide function for Y
var dataView = new google.visualization.DataView(dataTable);
// y1=2x+7
var yCol1 = {
calc: function (data, row) {
return (2 * data.getValue(row, 0)) + 7;
},
type: 'number',
label: 'Y1'
};
// use above object as Y1
dataView.setColumns([0, yCol1]);
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
// draw Y2 when chart finishes drawing
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
// add Y2 column
dataView.setColumns([0, yCol1, {
// y2=y1+(2x-1)
calc: function (data, row) {
//use reference to previous dataView
return dataView.getValue(row, 1) + ((2 * data.getValue(row, 0)) - 1);
},
type: 'number',
label: 'Y2'
}]);
chart.draw(dataView, {
series: {
1: {
lineWidth: 0,
pointSize: 8
}
}
});
});
chart.draw(dataView);
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
the same concept can be used to avoid having an array for the X values as well
just need to set an initial number of rows on a DataTable
see following working snippet...
google.charts.load('current', {
callback: function () {
// create blank table for the view
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('number', 'X');
dataTable.addRows(20);
// use DataView to provide function for X
var dataView = new google.visualization.DataView(dataTable);
var xCol = {
calc: function (data, row) {
return (row + 1) * 0.3;
},
type: 'number',
label: 'X'
};
dataView.setColumns([xCol]);
// function for Y --> y1=2x+7
var yCol1 = {
calc: function (data, row) {
return (2 * dataView.getValue(row, 0)) + 7;
},
type: 'number',
label: 'Y1'
};
dataView.setColumns([xCol, yCol1]);
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
// draw Y2 when chart finishes drawing
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
// add Y2 column
dataView.setColumns([xCol, yCol1, {
// y2=y1+(2x-1)
calc: function (data, row) {
//use reference to previous dataView
return dataView.getValue(row, 1) + ((2 * data.getValue(row, 0)) - 1);
},
type: 'number',
label: 'Y2'
}]);
chart.draw(dataView, {
series: {
1: {
lineWidth: 0,
pointSize: 8
}
}
});
});
chart.draw(dataView);
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How to use image in background instead of color for every column in google chart?

I am using google chart. I have created a column chart. In column chart I want to show the background image instead of background color in every column. Is it possible in google chart? How can I do this? Please share with me if any one have any idea.
My jsfiddle is here: http://jsfiddle.net/8fks1edf/
In image, I have marked where I want changes.
My Codes:
<div id="e_mcf" style="height: 400px; width: 600px;"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', 'ABCD');
dataTable.addColumn('number', 'Percentage');
dataTable.addColumn({type: 'string', role: 'annotation'});
dataTable.addColumn({type: 'string', role: 'style'});
dataTable.addRows([
['AB', 61, '61%','#FF8B00'],
['CD', 90,'90%', '#FF2D00'],
['EF', 70,'70%','#0C8E86'],
['GH', 85,'85%','#0779CF'],
['IJ', 70,'70%','#27486B']
]);
var options = {
vAxis: {gridlines: {color: 'transparent', count: 0}, minValue: 0},
legend: 'none',
backgroundColor: { fill:'transparent' },
isStacked: true,
annotations: {
textStyle: {
fontName: 'Lucida Fax',
fontSize: 10,
bold: true,
color: '#fff',
auraColor: 'transparent',
}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('e_mcf'));
chart.draw(dataTable, options);
}
</script>
Creating image via svg pattern, appending it to the def and filling with it via fill attribute.
enableInteractivity must be set to false.
window.google.visualization.events.addListener(chart, 'ready', function () {
var rectan = $('g g:first-of-type g:nth-of-type(2) rect');
var patt = document.createElementNS('http://www.w3.org/2000/svg', 'pattern');
patt.setAttribute('id', 'img1');
patt.setAttribute('patternUnits', 'userSpaceOnUse');
patt.setAttribute('width', '20');
patt.setAttribute('height', '287');
var image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '../Images/bar.png');
image.setAttribute('x', '0');
image.setAttribute('y', '0');
image.setAttribute('width', '20');
image.setAttribute('height', '287');
var defs = document.getElementsByTagName('defs')[0];
patt.appendChild(image);
defs.appendChild(patt);
for (var i = 0; i < rectan.length; i++) {
rectan[i].setAttribute("fill", "url(#img1)");
}}
rectan is a rect element inside the column chart. You just need to change fill attribute for all "pie slices" after first drawing of the chart.

Unable to Show Labels in Google Scatter Chart

I seem to be unable to get this Google Chart Scatter Plot to display the score.partner as a label. I can only get them to show as tooltips.
What am I doing wrong?
drawChart: function() {
var self = this;
var gdpMin = parseFloat(self.scores[0].gdpScore);
var gdpMax = gdpMin;
var teaMin = parseFloat(self.scores[0].teaScore);
var teaMax = teaMin;
var data = new google.visualization.DataTable();
data.addColumn('number', 'GDP Score');
data.addColumn('number', 'TEA Score');
data.addColumn({type:'string', role:'label'});
$.each(self.scores, function(i, score) {
gdpScore = parseFloat(score.gdpScore);
teaScore = parseFloat(score.teaScore);
data.addRows([[gdpScore, teaScore, score.partner]]);
if (gdpScore < gdpMin) gdpMin = gdpScore;
if (gdpScore > gdpMax) gdpMax = gdpScore;
if (teaScore < teaMin) teaMin = teaScore;
if (teaScore > teaMax) teaMax = teaScore;
});
var options = {
title: 'GDP and TEA Scores',
hAxis: {title: 'GDP', minValue: gdpMin, maxValue: gdpMax},
vAxis: {title: 'TEA', minValue: teaMin, maxValue: teaMax},
legend: 'none',
colors: ['#3B7CBF']
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
From user asgallant in Google Visualization API Group:
You want to label individual points on a ScatterChart? That isn't
supported. Depending on the structure of your data, you may be able
to use a LineChart in a manner similar to a ScatterChart. See an
example here: jsfiddle.net/asgallant/YFMga/
There you have it. Labels are not supported for scatter plots using the Google Visualization API.
jqPlot may be an acceptable alternative.

Categories