Google charts - Labels are not showing - javascript

I was trying to create 3 charts using google charts in a single line.but it not showing the labels for the values and we can see there is lot of space was vacant in between the charts.is there any way to remove that space and show the labels properly in the graph?
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 5],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
pieSliceText: 'value',
pieHole: '0.5',
legend: {
position: 'labeled',
labeledValueText: 'both',
textStyle: {
color: 'blue',
fontSize: 14
}
},
};
var chart1 = new google.visualization.PieChart(document.getElementById('chart1'));
var chart2 = new google.visualization.PieChart(document.getElementById('chart2'));
var chart3 = new google.visualization.PieChart(document.getElementById('chart3'));
options.title = 'industries For USA';
chart1.draw(data, options);
options.title = 'Categories For USA';
chart2.draw(data, options);
options.title = 'Categories For Construction';
chart3.draw(data, options);
}
.chart-wrapper {
float: left;
width: 33%;
}
.top-five-charts {
width: 100%;
display: block;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="top-five-charts">
<div class="chart-wrapper">
<div id="chart1" class="insight-pie"></div>
</div>
<div class="chart-wrapper">
<div id="chart2" class="insight-pie"></div>
</div>
<div class="chart-wrapper">
<div id="chart3" class="insight-pie"></div>
</div>
</div>
Here is the output in normal screen

Just add this line on your JavaScript code before drawing the charts:
options.chartArea = {left: '10%', width: '100%', height: '65%'};
I've also changed the legend font size to 10.
It will look like this:
Here's the JSFiddle illustrating it: https://jsfiddle.net/6r3ms2tz/

You should have a look responsive design principles and please check out this link: https://developers.google.com/chart/interactive/docs/basic_customizing_chart
Simply change: 'legend':'right' according to the your choice.

After several tries, below worked:
Code:
let options = {
legend: {
position: "labeled",
},
chartArea: {
width: "100%"
}
};
HTML for my case is below because I am using https://github.com/FERNman/angular-google-charts
<google-chart
style="width: 100%; height: 100%;"
>
</google-chart>
HTML for your case:
<div id="chart1" class="insight-pie" style="width: 100%; height: 100%;" ></div>
Hope that helps.

Related

Add label in the middle of Google pie chart donut

I am using the google charts library to create donut charts. I wanted to know if it was possible to add a label in the middle of my donut chart just as this:
I checked in the google description of options and couldn't find anything. here is how i generate my charts.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("visualization", "1", {packages:["corechart"]});
google.charts.setOnLoadCallback(init);
function drawChart(myID,titler,known,unknown) {
var data = google.visualization.arrayToDataTable([
['Knowledge', 'Out of 10'],
['Known', known],
['Unknown', unknown]
]);
var options = {
title: titler,
pieHole: 0.7,
colors: ['#000000', '#cdcdcd'],
pieSliceText: 'none',
legend:{position: 'none'},
tooltip:{text:'percentage'},
tooltip:{textStyle:{fontSize: 12}}
};
var chart = new google.visualization.PieChart(document.getElementById(myID));
chart.draw(data, options);
}
function init(){
drawChart('donutchart1','VB.NET',8,2);
drawChart('donutchart2','Javascript',4,6);
}
</script>
And my HTML to style my output:
<table class="Charts">
<tr>
<td><div id="donutchart1" style="width: 256px; height: 256px;"></div></td>
<td><div id="donutchart2" style="width: 256px; height: 256px;"></div></td>
</tr>
</table>
You can add an overlay div, centered on each donut chart, and set the following style attributes:
For the table cell:
position: relative;
For the overlay div:
position: absolute;
width: same as the donut width
line-height: same as the donut height
text-align: center;
The attribute position: relative is set on the table cell so that the absolute position of the overlay div is relative to the cell. The text-align attribute centers the text horizontally, the line-height attribute centers the text vertically.
google.charts.load("visualization", "1", { packages: ["corechart"] });
google.charts.setOnLoadCallback(init);
function drawChart(myID, titler, known, unknown) {
var data = google.visualization.arrayToDataTable([
['Knowledge', 'Out of 10'],
['Known', known],
['Unknown', unknown]
]);
var options = {
title: titler,
pieHole: 0.7,
colors: ['#000000', '#cdcdcd'],
pieSliceText: 'none',
legend: { position: 'none' },
tooltip: { text: 'percentage' },
tooltip: { textStyle: { fontSize: 12 } }
};
var chart = new google.visualization.PieChart(document.getElementById(myID));
chart.draw(data, options);
}
function init() {
drawChart('donutchart1', 'VB.NET', 8, 2);
drawChart('donutchart2', 'Javascript', 4, 6);
}
.donutCell
{
position: relative;
}
.donutDiv
{
width: 256px;
height: 256px;
}
.centerLabel
{
position: absolute;
left: 2px;
top: 2px;
width: 256px;
line-height: 256px;
text-align: center;
font-family: Arial, Helvetica, sans-serif;
font-size: 36px;
color: maroon;
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<table class="Charts">
<tr>
<td class="donutCell">
<div id="donutchart1" class="donutDiv"></div>
<div class="centerLabel">8/10</div>
</td>
<td class="donutCell">
<div id="donutchart2" class="donutDiv"></div>
<div class="centerLabel">4/10</div>
</td>
</tr>
</table>
Google Visualization uses SVG for the graphics, so if we want to reposition the SVG <text> we have a number of JavaScript methods at our disposal. If we use the Dev Console and dig into the charts, we will finally reach the lowest level that being the <text> element. Notice there's 2 attributes that look like XY coordinates. I wrote a function called centerText() that'll manipulate those particular attributes, and AFAIK, should be able to navigate through most Google Visualization Chart SVG layouts.
There's a bunch of commented out lines in this function because I was going to have it calculate horz/vert center, but I found out that the <text> tag doesn't have a <length>, so I'll leave that when I have more time.
function centerText(chart, idx, X, Y) {
idx === 'undefined' || idx === null || idx === NaN ? 0 : idx;
var cht = document.querySelector(chart);
var txt = document.querySelectorAll(chart + " text");
//var chW = cht.width/2;
//var chH = cht.height/2;
//var txW = txt[idx].width/2;
//var txH = txt[idx].height/2;
//var W = chW - txW;
//var H = chH - txH;
txt[idx].setAttribute('x', X);
txt[idx].setAttribute('y', Y);
}
/* chart [string][REQUIRED ]: Id of chart - ex. #donutchart1
|| idx [number][DEFAULT: 0]: Index number of <text>
|| X [number][REQUIRED ]: Set X coordinate of <text>
|| Y [number][REQUIRED ]: Set Y coordinate of <text>
*/
SNIPPET
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Google Visualization Dohnut Chart Text Position</title>
<style>
</style>
</head>
<body>
<table class="Charts">
<tr>
<td>
<div id="donutchart1" style="width: 256px; height: 256px;"></div>
</td>
<td>
<div id="donutchart2" style="width: 256px; height: 256px;"></div>
</td>
</tr>
</table>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load("visualization", "1", {
packages: ["corechart"]
});
google.charts.setOnLoadCallback(init);
function drawChart(chartID, heading, known, unknown) {
var chart = new google.visualization.PieChart(document.getElementById(chartID));
var data = google.visualization.arrayToDataTable([
['Knowledge', 'Out of 10'],
['Known', known],
['Unknown', unknown]
]);
var options = {
title: heading,
pieHole: 0.7,
colors: ['#000000', '#cdcdcd'],
pieSliceText: 'none',
legend: {
position: 'none'
},
tooltip: {
text: 'percentage'
},
tooltip: {
textStyle: {
fontSize: 12
}
}
};
chart.draw(data, options);
}
function centerText(chart, idx, X, Y) {
var cht = document.querySelector(chart);
var txt = document.querySelectorAll(chart + " text");
//var chW = cht.width/2;
//var chH = cht.height/2;
//var txW = txt[idx].width/2;
//var txH = txt[idx].height/2;
//var W = chW - txW;
//var H = chH - txH;
txt[idx].setAttribute('x', X);
txt[idx].setAttribute('y', Y);
}
function init() {
drawChart('donutchart1', 'VB.NET', 8, 2);
drawChart('donutchart2', 'Javascript', 4, 6);
centerText('#donutchart1', 0, 112, 130);
centerText('#donutchart2', 0, 106, 130);
}
</script>
</body>
</html>
I'd just like to automate the #zer00ne answer, so that we don't have to set the X and Y manually. The text will always be in the center regardless the length of the text
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport">
<title>Google Visualization Dohnut Chart Text Position</title>
<style>
#test_font{
position: absolute;
visibility: hidden;
height: auto;
width: auto;
white-space: nowrap;
}
</style>
</head>
<body>
<table class="Charts">
<tr>
<td>
<div id="donutchart1" style="width: 256px; height: 256px;"></div>
</td>
<td>
<div id="donutchart2" style="width: 256px; height: 256px;"></div>
</td>
</tr>
</table>
<div id="test_font"></div>
<script src="https://www.gstatic.com/charts/loader.js">
</script>
<script>
google.charts.load("visualization", "1", {
packages: ["corechart"]
});
google.charts.setOnLoadCallback(init);
function drawChart(chartID, heading, known, unknown) {
var chart = new google.visualization.PieChart(document.getElementById(chartID));
var data = google.visualization.arrayToDataTable([
['Knowledge', 'Out of 10'],
['Known', known],
['Unknown', unknown]
]);
var options = {
title: heading,
pieHole: 0.7,
colors: ['#000000', '#cdcdcd'],
pieSliceText: 'none',
legend: {
position: 'none'
},
tooltip: {
text: 'percentage'
},
tooltip: {
textStyle: {
fontSize: 12
}
}
};
chart.draw(data, options);
}
function centerText(chart) {
var cht = document.querySelector(chart);
var txt = document.querySelector(chart + " text");
var test_txt = document.querySelector('#test_font');
test_txt.innerHTML = txt.innerHTML;
test_txt.style.fontFamily = txt.getAttribute('font-family');
test_txt.style.fontSize = txt.getAttribute('font-size') + 'px';
test_txt.style.fontWeight = txt.getAttribute('font-weight');
var X = (cht.clientWidth-test_txt.clientWidth)/2;
var Y = ((cht.clientHeight-test_txt.clientHeight)/2) + 1*document.querySelectorAll(chart + " rect").item(1).getAttribute('height');
txt.setAttribute('x', X);
txt.setAttribute('y', Y);
}
function init() {
drawChart('donutchart1', 'VB.NET', 8, 2);
drawChart('donutchart2', 'Javascript', 4, 6);
centerText('#donutchart1');
centerText('#donutchart2');
}
</script>
</body>
</html>

I'm displaying a gauge chart in my site and the chart is inside a loop. But the chart is displayed only once. How to solve it?

I have placed this following code inside a loop and the chart is not displaying as desired.I have used google gauge chart to display the age of University. I have also attached the screenshot for more reference.
<h5>Age of <span class="text-primary"><?php echo $uni_name; ?></span></h5>
<?php
$est=date('Y')-$uni_establish;
?>
<p style="font-family: Serif; font-size: 170px; color:green; align:center"><b><?php echo $est;?></b></p>
<script type="text/javascript">
google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Age', <?php echo $est;?>],
]);
var options = {
width: 600, height: 320,
yelloFrom: 0, yellowTo: 100,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="width: 600px; height: 320px;"></div>
</section>
If this code is inside the loop means div with id chart_div will be appear multiple times, use an increment variable.

Google Charts Timeline grid - change timeline label span

I'm using Google Charts API to draw timeline of a multipart process. Right now it is adjusted automatically; for the chart shown below the window between grid lines is two days, and if I put more events there it can be a week or so making the chart unreadable.
How to set the chart to draw grid lines every day instead of adjusting it automatically? Or is there an alternative to this API I can use its source code to customize?
Make it as responsive, this links is an example. Check it out
https://codepen.io/flopreynat/pen/BfLkA
HTML:
<div class="row">
<div class="col-md-12 text-center">
<h1>Make Google charts responsive</h1>
<p>Full blog post details on my blog</p>
</div>
<div class="col-md-4 col-md-offset-4">
<hr />
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<div id="chart_div1" class="chart"></div>
</div>
<div class="col-md-6">
<div id="chart_div2" class="chart"></div>
</div>
</div>
CSS:
.chart {
width: 100%;
min-height: 450px;
}
JS:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart1);
function drawChart1() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart2);
function drawChart2() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2013', 1000, 400],
['2014', 1170, 460],
['2015', 660, 1120],
['2016', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div2'));
chart.draw(data, options);
}
$(window).resize(function(){
drawChart1();
drawChart2();
});
// Reminder: you need to put https://www.google.com/jsapi in the head of your document or as an external resource on codepen //
It may disppoinsed you that there is no way to set steps for a continuous chart.
But you can set gridlines:{count: } according to your step and timeline width.

Google Chart doesn't display when drawing multiple charts dynamically

I receive some datas with ajax, and I would like to display it as google line charts. I don't know how many chart I have to display, so I have made it dynamic using a javascript forEach to call my function drawchart();
Here I receive the datas :
$j.ajax({
type: "GET",
url: "../"+folder_destination+"slimrest/getValues",
data: "",
success: function(msg){
msg.forEach(function(entry) {
drawchart(entry['id'], entry['data']);
});
}
});
Here is my function which is supposed to add a div with a unique ID then draw the chart inside :
function drawchart(id_rec){
$j("#charts_cartes").append("<div id=\"gchart_"+id_rec+"\"></div>");
var data = new google.visualization.DataTable();
data.addColumn('number', 'max');
data.addColumn('number', 'min');
data.addColumn('number', 'Mesures');
//Will be dynamic as soon as I'll be able to print more than one chart
data.addRows([
[1, 37.8, 80.8],
[2, 30.9, 69.5]
]);
var options = {
width: 500,
height: 200
};
var chart = new google.charts.Line(document.getElementById('gchart_'+id_rec));
chart.draw(data, options);
}
I see my divs in the html code, but the second chart is never displayed.
It seems that the <svg></svg> balise is empty for one of the charts :
<div id="charts_cartes">
<div id="gchart_39">
<div style="position: relative; width: 500px; height: 200px;">
<div
style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%;">
<svg width="500" height="200">
<defs><!-- [chart code well displayed but too long to write here] --></defs>
</svg>
</div>
</div>
</div>
<div id="gchart_40">
<div style="position: relative; width: 500px; height: 200px;">
<div
style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%;">
<svg width="500" height="200">
<defs></defs></svg>
</div>
</div>
</div>
</div>
Problem fixed adding a setTimeout to the draw function of the googlechart :
setTimeout(function(){ chart.draw(data, options); }, 1000);
There must be some conflicts if drawing to much charts almost simultaneously ...
The solution above works, but setTimeout with just 1 millisecond works, so that if you're dynamically generating the charts with some display logic, it won't be loading for 1000 milliseconds.
So this also worked for me in an AngularJS app.
setTimeout(function(){ chart.draw(data, options); }, 1);

Styling Google Charts Table

I am trying to add CSS style to a Google Charts Table. I tried this:
https://developers.google.com/chart/interactive/docs/gallery/table#customproperties
on the first cell (Mike) but it didn't work. I set allowHtml to true in the options variable. How can I change the background, text color, etc. of the individual cells? Thank you.
<script type="text/javascript">
google.load('visualization', '1', {packages:['table']});
google.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Employee Name');
data.addColumn('date', 'Start Date');
data.addRows(3);
data.setCell(0, 0, 'Mike', {style: 'background-color:red;'});
data.setCell(0, 1, new Date(2008, 1, 28));
data.setCell(1, 0, 'Bob');
data.setCell(1, 1, new Date(2007, 5, 1));
data.setCell(2, 0, 'Alice');
data.setCell(2, 1, new Date(2006, 7, 16));
var options = {
allowHtml: true
};
// Create a formatter.
// This example uses object literal notation to define the options.
var formatter = new google.visualization.DateFormat({formatType: 'long'});
// Reformat our data.
formatter.format(data, 1);
// Draw our data
var table = new google.visualization.Table(document.getElementById('dateformat_div'));
table.draw(data, options);
}
</script>
How can I change the background, text color, etc. of the individual cells? Thank you.
Per #Bondye's comment, the answer is found in the developers guide.
https://developers.google.com/chart/interactive/docs/examples#custom_table_example
Define style rules that match your criteria:
<style>
.orange-background {
background-color: orange;
}
.orchid-background {
background-color: orchid;
}
.beige-background {
background-color: beige;
}
</style>
Apply them to the table when drawn.
var cssClassNames = {
'headerRow': 'italic-darkblue-font large-font bold-font',
'tableRow': '',
'oddTableRow': 'beige-background',
'selectedTableRow': 'orange-background large-font',
'hoverTableRow': '',
'headerCell': 'gold-border',
'tableCell': '',
'rowNumberCell': 'underline-blue-font'};
var options = {'showRowNumber': true, 'allowHtml': true, 'cssClassNames': cssClassNames};
var data = new google.visualization.DataTable();
//... add data here ...
var table = new google.visualization.Table(container);
table.draw(data, options);
Custom table formatting for google-charts was tricky for me:
It worked from the style: .tableRow { background-color:rgb(246, 253, 253); }
It also worked from standart css: tr:hover {background-color: ...;}
It sometimes worked only with !important css key: background-color: rgba(141, 186, 238, 0.76) !important;
Here's my working sample:
// Load the Visualization API and the controls package.
google.load('visualization', '1.0', { packages: ['table'] });
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawDashboard);
// Callback that creates and populates a data table,
// instantiates a dashboard, a range slider and a pie chart,
// passes in the data and draws it.
function drawDashboard() {
// Create our data table.
var data = google.visualization.arrayToDataTable([
['Sex', 'Name', 'Donuts eaten', 'Html'],
['Male', 'Michael', 5, '<input type="checkbox" id="1" name="check">'],
['Female', 'Elisa', 7, '<input type="checkbox" id="2" name="check">'],
['Male', 'Robert', 3, '<input type="checkbox" id="3" name="check">'],
['Male', 'John', 2, '<input type="checkbox" id="4" name="check">'],
['Female', 'Jessica', 6, '<input type="checkbox" id="5" name="check">'],
['Male', 'Aaron', 1, '<input type="checkbox" id="6" name="check">'],
['Female', 'Margareth', 8, '<input type="checkbox" id="7" name="check">'],
]);
var table = new google.visualization.Table(document.getElementById('table'));
var options =
{
allowHtml: true,
showRowNumber: true,
width: '100%',
height: '100%'
,
cssClassNames: {
headerRow: 'headerRow',
tableRow: 'tableRow',
oddTableRow: 'oddTableRow',
selectedTableRow: 'selectedTableRow',
// hoverTableRow: 'hoverTableRow',
headerCell: 'headerCell',
tableCell: 'tableCell',
rowNumberCell: 'rowNumberCell'
}
};
table.draw(data, options);
}
body
{
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
/* Tables */
th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: rgb(83, 133, 180);
border-color: rgb(151, 150, 168) !important;
color: white;
}
.oddTableRow {
background-color:rgb(232, 246, 247);
}
.tableRow { background-color:rgb(246, 253, 253); }
tr:hover {background-color: rgba(233, 235, 154, 0.76) !important;}
.selectedTableRow {
background-color: rgba(141, 186, 238, 0.76) !important;
}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Google Charts. Custom HTML & CSS in table</h1>
<div id="table"></div>
</body>
</html>
For more modern widgets and charts you can apply custom css to Google Charts see this repo for already implemented styles
https://github.com/weekdone/GoogleChartStyles

Categories