Google Charts Pie Chart always showing 100% - javascript

I am using the following code to to draw a piechart. problem is it is always showing a full circle. The code works fine for a line chart (commented). Is the data format that I'm using wrong in someway? JSFiddle here
<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 json_data = new google.visualization.DataTable('{"cols":[{"label":"Class","type":"string"},{"label":"Deals","type":"number"}],"rows":[{"c":[{"v":"Heavy","f":null},{"v":"5","f":null}]},{"c":[{"v":"Medium","f":null},{"v":"101","f":null}]},{"c":[{"v":"Light","f":null},{"v":"18","f":null}]}]}');
//var chart = new google.visualization.LineChart(document.getElementById('donutchart'));
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
var options = {
title: '',
chartArea: {
left: 40,
top: 10,
width: "90%",
height: "80%"
},
legend: {
position: "none"
},
colors: ['#468ba9', "#67696c"],
pieHole: 0.4,
};
chart.draw(json_data, options);
}
</script>
<body>
<div id="donutchart" style="width: 300px; height: 300px;"></div>
</body>
EDIT: I would need a solution with json data as I cannot change to input data

As per dlaliberte's comment, though i had declared "Deals" to be of type number, the data passed was of type string.
Thus
{"cols":[{"label":"Class","type":"string"},{"label":"Deals","type":"number"}],"rows":[{"c":[{"v":"Heavy","f":null},{"v":"5","f":null}]},{"c":[{"v":"Medium","f":null},{"v":"101","f":null}]},{"c":[{"v":"Light","f":null},{"v":"18","f":null}]}]}
should become
{"cols":[{"label":"Class","type":"string"},{"label":"Deals","type":"number"}],"rows":[{"c":[{"v":"Heavy","f":null},{"v":5,"f":null}]},{"c":[{"v":"Medium","f":null},{"v":101,"f":null}]},{"c":[{"v":"Light","f":null},{"v":18,"f":null}]}]}
JS Fiddle: http://jsfiddle.net/Hzr47/2/

This is because you tried to trick google !!
I just changed your data in to a more simpler collection. Also, I took the liberty to add one extra colour for your third pie in this case.
<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 json_data = google.visualization.arrayToDataTable([
['Class', 'Deals'],
['Heavy', 5],
['Medium', 101],
['Light', 18]
]);
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
var options = {
title: '',
chartArea: {
left: 40,
top: 10,
width: "90%",
height: "80%"
},
legend: {
position: "none"
},
colors: ['#468ba9', "#67696c", "#6cc96c"],
pieHole: 0.4,
};
chart.draw(json_data, options);
}
</script>
<body>
<div id="donutchart" style="width: 300px; height: 300px;"></div>
</body>

Related

How to increase space between horizontal bars in google stacked bar chart

I am using google charts, which shows the stacked bar chart. I tried groupwidth, but help well increasing the width.
Any help is much appreciated.
function drawChart() {
// Define the chart to be drawn.
var data = google.visualization.arrayToDataTable([
['name', 'data1', 'data2','data3'],
['w1', 40,20,40],
['w2', 40,20,40],
['w2', 40,20,40],
['w2', 40,20,40], ['w2', 40,20,40],
['w2', 40,20,40], ['w2', 40,20,40],
['w2', 40,20,40],
]);
var options = {title: 'Percentage of Risk', isStacked:true,bar: {width:"200%",height:"1200%",gap:"10%"}};
// Instantiate and draw the chart.
var chart = new google.visualization.BarChart(document.getElementById('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
#container {
width: 550px; height: 1200px; margin: 0 auto
}
<html>
<head>
<title>Google Charts Tutorial</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"></script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['corechart']});
</script>
</head>
<body>
<div id = "container">
</div>
</body>
</html>
To increase the width of a group of bars in Google Charts, you have to use the groupWidth configuration.
The syntax for this configuration is:
bar: {groupWidth: '100%'}
which is placed in the chart options variable.
So for your specific code it would be:
var options = {title: 'Percentage of Risk',
isStacked:true,
bar: {groupWidth: '100%'}};
The width of the group of bars can be specified as pixels, for example 75 or as a percentage such as 50%. For the percentage data type, 100% means no space between the bars.
Official documentation for charts configurations: https://developers.google.com/chart/interactive/docs/gallery/columnchart#configuration-options
If you want to increase width then you should try this, I have also put in my code:
<script>
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Chart data
var data = google.visualization.arrayToDataTable([
['SALES', 'FINANCIAL YEAR'],
['FY-16',100],
['FY-17', 230],
['FY-18', 520],
['FY-19', 940],
['FY-20', 1400],
['FY-21', 2000]
]);
//Chart Custom Options
var options = {
title: 'SALES',
vAxis: { title: 'SALES', ticks: [0, 200, 400, 600, 800, 1000, 1200,1400,1600,1800,2000,2200] },
hAxis: { title: 'FINANCIAL YEAR' },
seriesType: 'bars',
colors: ['#f58a07'],
legend: { position: 'bottom', maxLines: 2, pagingTextStyle: { color: '#374a6f' }, scrollArrows: { activeColor: '#666', inactiveColor: '#ccc' } },
series: { 1: { pointSize: 2, type: 'line' } },
animation: {
duration: 1000,
easing: 'linear',
startup: true
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
$(window).resize(function () {
drawVisualization();
});
</script>`enter code here`
----------
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="chart_div" class="chart"></div>
</div>
</div>
</div>
----------
<style type="text/css">
.chart {
width: 100%;
min-height: 500px;
}
#media(max-width: 667px) {
.chart {
width: 350px;
min-height: 400px;
}
}
</style>

How do I show annotations on my Google Chart that extracts data from a Google Spreadsheet?

I have a Google Chart that displays some data.
Here is the HTML -
<div id="chart"></div>
Here is the CSS -
html,
body {
width: 100%;
height: 100%;
}
#chart {
width: 100%;
}
Here is the JS -
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:B");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
var data = response.getDataTable();
var chartAreaHeight = data.getNumberOfRows() * 10;
var chartHeight = chartAreaHeight + 70;
var options = {
title: "Andaman & Nicobar Islands",
legend: "none",
vAxis: {
title: "Year",
format: "0",
},
hAxis: {
title: "Rainfall (in mm)"
},
height: chartHeight,
chartArea: {
height: chartAreaHeight,
top: "100",
right: "100",
bottom: "100",
left: "100"
}
};
var chart = new google.visualization.BarChart(document.getElementById("chart"));
chart.draw(data, options);
};
window.onresize = function (event) {
chart.draw(data, options);
};
Now, I want to display annotations beside the bars displaying the value of that bar. How do I do that?
Here is the JSFiddle
to add annotations, add a column for the annotation text, directly after the column with the values.
in the following example, a DataView is used to add a calculated column for the annotations.
also, the resize function needs to be included in the same scope as the chart.
in the fiddle provided, an error will occur when the window is resized,
as the chart, data, and options variables are not available.
see following, working example...
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:B");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
var data = response.getDataTable();
var chartAreaHeight = data.getNumberOfRows() * 10;
var chartHeight = chartAreaHeight + 70;
var options = {
// add text style for annotation
annotations: {
textStyle: {
fontSize: 8
}
},
title: "Andaman & Nicobar Islands",
legend: "none",
vAxis: {
title: "Year",
format: "0"
},
hAxis: {
title: "Rainfall (in mm)"
},
height: chartHeight,
chartArea: {
height: chartAreaHeight,
top: "100",
right: "100",
bottom: "100",
left: "100"
}
};
// format data for annotation
var formatter = new google.visualization.NumberFormat({pattern: '#,##0.0'});
formatter.format(data, 1);
// use view to add annotation column
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}]);
var chart = new google.visualization.BarChart(document.getElementById("chart"));
chart.draw(view, options);
window.addEventListener('resize', function () {
chart.draw(view, options);
}, false);
}
html,
body {
width: 100%;
height: 100%;
}
#chart {
width: 100%;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

How to place chart top and bottom?

I want to display one of the chart underneath the other but for now only the 1st chart is showing and I can't seem to display the other chart at the bottom of it. Also, how do I make the chart align to the middle?
<section>
<html>
<div class="container"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchart_values" style="width: 1200px; height: 700px;"></div>
<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Week", "# of F2F=0"],
["Copper", 8.94],
["Silver", 10.49],
["Gold", 19.30],
["Platinum", 0]
]);
var view = new google.visualization.DataView(data);
var options = {
title: "Period: ASEAN 2Q F2F = 0 Dashboard",
'backgroundColor': 'transparent',
width: 600,
height: 400,
bar: {groupWidth: "70%"},
legend: { position: "right" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
</script>
<div id="piechart_3d" style="width: 1200px; height: 700px;"></div>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Number of calls made', 'Number of people'],
['F2F = 0', 6],
['1 < F2F < 5', 8],
['F2F > 9', 5]
]);
var options = {
title: 'Period: ASEAN2QWK3',
titleTextStyle: {
fontSize: 21
},
'backgroundColor': 'transparent',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
</script>
</html>
</section>
You are calling '.load' method twice, which is incorrect.
Just comment below line for second chart and both chart will be loaded.
google.charts.load("current", {packages:["corechart"]});

Google Line Chart Add Hover Title To X Value

When I hover over a point in my line chart/graph I get only the Y value and not the X value.
What I get:
36
Speed: 120
What I want:
Distance: 36
Speed: 120
Code:
<script type="text/javascript" src="https://www.google.com/jsapi" ></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', "Distance");
data.addColumn('number', "Speed");
data.addRows(<?php echo json_encode($DistanceSpeedArray, JSON_NUMERIC_CHECK); ?>);
var options = {
focusTarget: 'category',
backgroundColor: 'none',
chartArea: {
backgroundColor: 'transparent',
left: 40,
top: 40,
width: 1200,
height: 350
},
legend: {
position: 'top'
},
hAxis: {title: 'Distance (KM)', titleTextStyle: {color: 'black'}},
//vAxis: {title: 'Speed (KM/H)', titleTextStyle: {color: 'black'}},
colors: ['green'],
crosshair: {
orientation: 'vertical'
},
animation: {
startup: true,
duration: 5000
},
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
The above code is a complete code including the focusTarget: 'category' which still returns only the Y title. I have also included a screenshot.
You may apply a format to the Distance-column
new google.visualization.PatternFormat("Distance: {0}")
.format(data, [0], 0);
https://jsfiddle.net/6tf2fatz/
Basically you need to add focusTarget: 'category' for focus on a grouping of all data points along the major axis.
Try below code,
<script type="text/javascript" src="https://www.google.com/jsapi" ></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Distance');
data.addColumn('number', "Speed");
data.addRows(<?php echo json_encode($DistanceSpeedArray, JSON_NUMERIC_CHECK); ?>);
...
var options = { focusTarget: 'category' };
var chart = new google.visualization.LineChart(document.getElementById('your_div_chart'));
chart.draw(data, options);
}

Animating column chart from google charts

I'm having trouble coming up with a function that will animate a single column bar inside of my chart when I use a slider going back and forth..left and right.. I have read the animation docs on the Google Charts API documentation, but I am having a hard time understanding what I need to do.
Here is my code so far. Where would I start in figuring out how to animate just one of my bars using a slider I have made in titanium? I call the function updateChart() from my app.js file using the evalJS function. I have verified it works, by doing a console.log when my slider goes back and forth. I just can't seem to wrap my head around it how to apply this to animating a single column bar. Any thoughts are appreciated.
Set up Google Charts on my html page.
<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 data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([['',5,'#000000'], ['',5,'#ffffff'],['',5,'#666666'],['', 5,'#cccccc']]);
var options =
{
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
function updateChart() {
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
EDITED CODE:
<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 data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([['',5,'#000000'], ['',5,'#ffffff'],['',5,'#666666'],['', 5,'#cccccc']]);
var options = {
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
function updateChart(value) {
data.setValue(0, 1, value);
chart.draw(data, options);
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Slider Hook Code in separate file (app.js) Titanium Platform
var sliderBarOne = Titanium.UI.createSlider({
top: '310',
left: '610',
min: '0',
max: '10',
width: '37%',
value: '5',
backgroundImage: 'assets/sliderBar.png'
});
sliderBarOne.addEventListener('change', function(e) {
chartView.evalJS("updateChart('" + e.value + "');");
});
You need to hook up an event listener for your slider that calls the updateChart function. The updateChart function should get the value from the slider and change the value in the DataTable, then cal the chart's draw method. How you hook up an event listener to the slider is going to depend on the library you are using for the slider. Here's some example code that assumes your slider object has a change method to set a change event handler and a `getValue method to get the value of the slider:
[edit: added in your slider code]
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([
['',5,'#000000'],
['',5,'#ffffff'],
['',5,'#666666'],
['', 5,'#cccccc']
]);
var options = {
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
function updateChart(value) {
data.setValue(0, 1, value);
chart.draw(data, options);
}
// create slider
var sliderBarOne = Titanium.UI.createSlider({
top: '310',
left: '610',
min: '0',
max: '10',
width: '37%',
value: '5',
backgroundImage: 'assets/sliderBar.png'
});
sliderBarOne.addEventListener('change', function(e) {
updateChart(e.value);
});
chart.draw(data, options);
}

Categories

Resources