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
Related
I am building a map to show both the unemployment rate in regions and districts in Ghana. I would like to add the functionality to show either the male, the female, total or difference between the two. To do this I added a dropdown menu to filter and select either of the values, but how do I now get that value to represent in the map? As in, how do I update ['get', 'value'], to value mean total (the default), male, female, or difference?
This is my quarto code thusfar:
```
---
title: "About"
format:
html:
page-layout: custom
---
::: grid
::: g-col-4
This is a first test
```{=html}
<br>
<label for="data">Choose your dataset:</label>
<br>
<select name="data" id="dataselect">
<option value="https://raw.githubusercontent.com/Laurent-Smeets-GSS-Account/geojsons/main/geojsons_files/simplified_regions_and_districts272.geojson">ghana 272</option>
<option value="https://raw.githubusercontent.com/Laurent-Smeets-GSS-Account/geojsons/main/geojsons_files/unemployment_per_district.geojson">Unemployment rate</option>
</select>
```
```{=html}
<br>
<label for="sex">Choose your sex:</label>
<br><select name="sex" id="sexselect">
<option value="Value">Total</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Difference">Difference between male and female</option>
</select>
```
:::
::: g-col-8
some text in the second column
```{=html}
<div id='map'>
<div id="legend" class="legend">
<div><span style="background-color: #FFF8E8"></span>0%</div>
<div><span style="background-color: #FCD581"></span>5%</div>
<div><span style="background-color: #F3AA71"></span>10%</div>
<div><span style="background-color: #E97F61"></span>15%</div>
<div><span style="background-color: #D52941"></span>20%</div>
<div><span style="background-color: #B71B3B"></span>30%</div>
<div><span style="background-color: #990D35"></span>100%</div>
</div>
<div class='map-overlay' id='features'><div id='pd'><p>Hover over a region</p></div>
</div>
```
```{=html}
<link href="https://api.mapbox.com/mapbox-gl-js/v2.11.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.11.0/mapbox-gl.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
body{margin: 0; padding: 1}
#map { margin:auto; width: 100%; height: 800px; }
#legend {position: absolute;
bottom: 0;
right: 0;
z-index: 1000;
margin-bottom: 30px;
margin-right:30px;
border-radius: 3px;
padding: 5px 10px;
background: white;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
</style>
<script>
$(document).ready(function(){
mapboxgl.accessToken = 'pk.eyJ1IjoibWFydGluLWFybm9sZCIsImEiOiJjbGI0NjVwOTMwNTltM3JvZmtkY3VqN2p5In0.GTqfQeF5FFKqyDEdl0zfXA';
const bounds = [
[-8,-1], // Southwest coordinates
[5, 16] // Northeast coordinates
];
const map = new mapboxgl.Map({
container: 'map', // container ID
// Choose from Mapbox's core styles, or make your own style with Mapbox Studio
style: 'mapbox://styles/mapbox/light-v11', // style URL
projection: 'globe', // Display the map as a globe, since satellite-v9 defaults to Mercator
zoom: 6, // starting zoom
center: [0, 7.5], // // starting center in [lng, lat]
maxBounds: bounds // Set the map's geographical boundaries.
});
const zoomThreshold = 7;
map.on('style.load', () => {
map.setFog({});
map.addSource('the_source', {
type: 'geojson',
data: 'https://raw.githubusercontent.com/Laurent-Smeets-GSS-Account/geojsons/main/geojsons_files/simplified_regions_and_districts272.geojson'
});
map.addLayer({
'id': 'ghana1',
'type': 'fill',
'source': 'the_source',
'maxzoom': zoomThreshold,
'paint': {
'fill-color': [
'interpolate',
['linear'],
['get', 'value'],
0,
'#FFF8E8',
0.05,
'#FCD581',
0.1,
'#F3AA71',
0.15,
'#E97F61',
0.2,
'#D52941',
0.3,
'#B71B3B',
1.0,
'#990D35'
],
'fill-opacity': 0.75
},
filter: ['==', 'level', 'Region']
});
map.addLayer({
'id': 'ghana2',
'type': 'fill',
'source': 'the_source',
'minzoom': zoomThreshold,
maxBounds: bounds, // Set the map's geographical boundaries.
'paint': {
'fill-color': [
'interpolate',
['linear'],
['get', 'value'],
0,
'#FFF8E8',
0.05,
'#FCD581',
0.1,
'#F3AA71',
0.15,
'#E97F61',
0.2,
'#D52941',
0.3,
'#B71B3B',
1.0,
'#990D35'
],
'fill-opacity': 0.75
},
filter: ['==', 'level', 'District']
});
});
$( "#dataselect" ).change(function() {
$( "#dataselect option:selected" ).each(function() {
map.getSource('the_source').setData( $(this).val() );
});
});
$( "#sexselect" ).change(function() {
$( "#sexselect option:selected" ).each(function() {
map.getSource('sexselect').setData( $(this).val() );
});
});
map.on('mousemove', (event) => {
const states = map.queryRenderedFeatures(event.point, {
layers: ['ghana2', 'ghana1']
});
document.getElementById('pd').innerHTML = states.length
? `<h3>${states[0].properties.stat}</h3><h4>${states[0].properties.name}</h4><p><strong><em>${Math.trunc(states[0].properties.value *10000)/100}%</strong> ${states[0].properties.stat}</em></p>`
: `<h3>${states[0].properties.stat}</h3><p>Hover over a state!</p>`;
});
});
</script>
```
:::
:::
```
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.
I embedded Google Charts in my application and it is displyed at UI side like below image:
also dropdown list is displayed as given in below image:
I attached one link and one button in charts as "Export" and "Table Data" which seen in above image. And inside "Export" I provide a drop down list. In other charts I only able to get "Export" link only and not able to get drop down list as well.
To embedded various charts I used separate JSP file for each charts like if I embedded column Bar and Pie chart then I create different JSP files for both charts.
for developing this I used 2 JSP files one is dashboardLayout.jsp and for embedded various charts I used foreach loop.
code snippet is given below:
dashboardLayout.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<style>
button {
color:#fff;
background-image: linear-gradient(to bottom,#337ab7 0,#265a88 100%);
padding: 5px 10px;
font-size: px;
line-height: 1.5;
border-radius: 3px;
cursor: pointer;
border-color: #265a88;
text-shadow: 0 -1px 0 rgba(0,0,0,.2);
box-shadow: inset 0 1px 0 rgba(255,255,255,.15),0 1px 1px rgba(0,0,0,.075);
}
button:hover{
background-image: linear-gradient(to top,#337ab7 0,#265a88 100%);
box-shadow: inset 0 1px 0 rgba(255,255,255,.25),0 1px 1px rgba(0,0,0,.175);
}
</style>
<style>
.click {
background:none!important;
border:none;
padding:0!important;
font-family:Helvetica Neue,Helvetica,Arial,sans-serif; /*input has OS specific font-family*/
color:#333;
cursor:pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdownhover {
font-family: Helvetica Neue,Helvetica,Arial,sans-serif;
font-size: 15px;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #666666;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: white;
padding: 2px 2px;
text-align: left;
text-decoration: none;
display: block;
font-family: Helvetica Neue,Helvetica,Arial,sans-serif;
}
.dropdown-content a:hover {background-color: #111111}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
</style>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart','table','timeline','charteditor']});
$(document).ready(function() {
$(".column").sortable({
connectWith: ".column",
handle: ".portlet-header",
cancel: ".portlet-toggle",
placeholder: "portlet-placeholder ui-corner-all",
stop : function(event, ui) {
var currentDivId = this.id;
var parentDivId = $(ui.item).parents().attr('id')
console.log('javascript ==> currentDivId : '+currentDivId+", parentDivId : "+parentDivId);
if(currentDivId != parentDivId){
updateDashboardChartOrderAjaxFunction(currentDivId, parentDivId);
}
}
})
$(".portlet")
.addClass( "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" )
.find( ".portlet-header" )
.addClass( "ui-widget-header ui-corner-all" )
.prepend( "<span class='ui-icon ui-icon-minusthick portlet-toggle'></span>");
});
function chartScrollBarHide(divId) {
$('#'+divId).css("overflow-x", "hidden");
$('#'+divId).css("margin-bottom", "48px");
}
</script>
<c:forEach var="chart" items="${chartPropertiesList}" varStatus="theCount">
<div class="column" id="${chart.merchantReportId}/${theCount.count}">
<div class="portlet" id="${chart.chartHeaderTitle}">
<div class="portlet-header">${chart.chartHeaderTitle}</div>
<c:if test="${not empty chart.merchantReportData.responseData or not empty chart.merchantReportData.categoriesJsonData}">
<div style="text-align: center; padding: 5px 0px;" class="boson-font">
Change Chart :
<select id="changeChart${theCount.count}" name="changeChart${theCount.count}" style="font-family: Helvetica Neue,Helvetica,Arial,sans-serif;font-size: 15px;"
onchange="changeChartAjaxFunction('${chart.merchantReportId}','${chart.chartDivId}',this.value);" >
<c:forEach var="chartType" items="${chartTypeNameList}">
<c:choose>
<c:when test="${chartType.key eq chart.chartName}">
<option value="${chartType.key}" selected="selected">${chartType.value}</option>
</c:when>
<c:otherwise>
<option value="${chartType.key}">${chartType.value}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
<div class="dropdown">
Export
<div class="dropdown-content" id="export"></div>
</div>
</div>
</c:if>
<c:choose>
<c:when test="${chart.chartName eq 'columnbar'}">
<jsp:include page="chartsview/columnBarChart.jsp">
<jsp:param name="chartDivId" value="${chart.chartDivId}"/>
<jsp:param name="jsondata" value="${chart.merchantReportData.responseData}"/>
<jsp:param name="linkedJsonData" value="${chart.merchantReportData.responseLinkedData}"/>
<jsp:param name="xaxisLable" value="${chart.xAxisLable}"/>
<jsp:param name="yaxisLable" value="${chart.yAxisLable}"/>
</jsp:include>
<div class="portlet-content" id="${chart.chartDivId}"> ColumnBar Chart load here </div>
</c:when>
<c:when test="${chart.chartName eq 'pie'}">
<jsp:include page="chartsview/pieChart.jsp">
<jsp:param name="chartDivId" value="${chart.chartDivId}"/>
<jsp:param name="jsondata" value="${chart.merchantReportData.responseData}"/>
<jsp:param name="linkedJsonData" value="${chart.merchantReportData.responseLinkedData}"/>
<jsp:param name="xaxisLable" value="${chart.xAxisLable}"/>
<jsp:param name="yaxisLable" value="${chart.yAxisLable}"/>
</jsp:include>
<div class="portlet-content" id="${chart.chartDivId}"> Pie Chart load here pie</div>
</c:when>
</c:choose>
</div>
</div>
<c:if test="${empty chart.merchantReportData.responseData and empty chart.merchantReportData.categoriesJsonData}">
<script type="text/javascript">
chartScrollBarHide('${chart.chartDivId}');
</script>
</c:if>
</c:forEach>
columBarChart.jsp
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart','table','timeline','charteditor']});
google.charts.setOnLoadCallback(drawChart);
var chartDivId = null;
var options = null;
var data = null;
var fileName = 'Test';
function AddNamespaceHandler() {
var svg = jQuery("#"+chartDivId+" svg");
svg.attr("xmlns", "http://www.w3.org/2000/svg");
svg.css('overflow','visible');
}
function drawChart() {
var chartData = [
['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Rwanda', 'Average'],
['2004/05', 165, 938, 522, 450, 614.6],
['2005/06', 135, 1120, 599, 288, 682],
['2006/07', 157, 1167, 587, 397, 623],
['2007/08', 139, 1110, 615, 215, 609.4],
['2008/09', 136, 691, 629, 366, 569.6]
];
chartDivId = "${param.chartDivId}";
//chartDivId="17Div2";
if(!chartDivId){
chartDivId = "${chartDivId}";
}
console.log("columnbar div id: " + chartDivId);
var xaxisLable = "${param.xaxisLable}";
if(!xaxisLable){
xaxisLable = "${xaxisLable}";
}
var yaxisLable = "${param.yaxisLable}";
if(!yaxisLable){
yaxisLable = "${yaxisLable}";
}
data = google.visualization.arrayToDataTable(chartData);
options = {
title: 'Monthly Coffee Production by Country',
hAxis: {title: xaxisLable},
vAxis: {title: yaxisLable},
width : "600",
height : "300"
};
var chart = new google.visualization.ColumnChart(document.getElementById(chartDivId));
google.visualization.events.addListener(chart, 'ready', AddNamespaceHandler);
chart.draw(data, options);
var exportsColumn="return xepOnline.Formatter.Format('"+chartDivId+"', {render:'download', mimeType:'application/pdf', filename:'"+fileName+"'})";
//jQuery('#export').html('Export To PDF');
var exportsColumn1="return xepOnline.Formatter.Format('"+chartDivId+"', {render:'download', mimeType:'image/svg+xml', filename:'"+fileName+"'})";
jQuery('#export').html('Export To PDF Export To Image');
// Chart Table Data - Start
jQuery('#tables').html('<button class="click" style="font-family: Helvetica Neue,Helvetica,Arial,sans-serif; box-shadow: 0 0 0 0;" data-toggle="modal" data-target="#openModal" onclick="loadExportChartTable();">Table Data</button>');
var buttons="return xepOnline.Formatter.Format('parent_table', {render:'download',mimeType:'application/pdf', filename:'"+fileName+"'})";
jQuery('#buttons_table').html('<button onclick="'+ buttons +'">PDF</button> <button onclick="dataTableToCSV();">EXCEL</button>');
/* jQuery('#buttons_table').append(" ");
jQuery('#buttons_table').append('<button onclick="dataTableToCSV();">EXCEL</button>'); */
// Chart Table Data - End
}
// Load the Export Chart table data
function loadExportChartTable() {
var table_data = new google.visualization.Table(document.getElementById('table_div'));
google.visualization.events.addListener(table_data, 'ready', AddNamespaceHandler);
table_data.draw(data, {showRowNumber: false, width: '100%', height: '100%'});
}
function dataTableToCSV() {
var dataTable_arg = data;
var dt_cols = dataTable_arg.getNumberOfColumns();
var dt_rows = dataTable_arg.getNumberOfRows();
var csv_cols = [];
var csv_out;
for (var i=0; i<dt_cols; i++) {
csv_cols.push(dataTable_arg.getColumnLabel(i).replace(/,/g,""));
}
csv_out = csv_cols.join(",")+"\r\n";
for (i=0; i<dt_rows; i++) {
var raw_col = [];
for (var j=0; j<dt_cols; j++) {
raw_col.push(dataTable_arg.getFormattedValue(i, j, 'label').replace(/,/g,""));
}
csv_out += raw_col.join(",")+"\r\n";
}
//return csv_out;
this.downloadCSV(csv_out, fileName);
}
function downloadCSV (csv_out, fileName) {
var blob = new Blob([csv_out], {type: 'text/csv;charset=utf-8'});
var url = window.URL || window.webkitURL;
var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
link.href = url.createObjectURL(blob);
link.download = fileName+".csv";
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, true);
link.dispatchEvent(event);
}
</script>
pieChart.jsp
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart','table','timeline','charteditor']});
google.charts.setOnLoadCallback(drawChart);
var chartDivId = null;
var options = null;
var data = null;
var fileName = 'Test';
function AddNamespaceHandler() {
var svg = jQuery("#"+chartDivId+" svg");
svg.attr("xmlns", "http://www.w3.org/2000/svg");
svg.css('overflow','visible');
}
var chartData = [
['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Rwanda', 'Average'],
['2004/05', 165, 938, 522, 450, 614.6],
['2005/06', 135, 1120, 599, 288, 682],
['2006/07', 157, 1167, 587, 397, 623],
['2007/08', 139, 1110, 615, 215, 609.4],
['2008/09', 136, 691, 629, 366, 569.6]
];
function drawChart() {
chartDivId = "${param.chartDivId}";
if(!chartDivId){
chartDivId = "${chartDivId}";
}
console.log("pieChart div id: " + chartDivId);
var xaxisLable = "${param.xaxisLable}";
if(!xaxisLable){
xaxisLable = "${xaxisLable}";
}
var yaxisLable = "${param.yaxisLable}";
if(!yaxisLable){
yaxisLable = "${yaxisLable}";
}
var data = google.visualization.arrayToDataTable(chartData);
var options = {
title: 'Monthly Coffee Production by Country',
hAxis: {title: xaxisLable},
vAxis: {title: yaxisLable},
width : "600",
height : "300"
};
var chart = new google.visualization.PieChart(document.getElementById(chartDivId));
google.visualization.events.addListener(chart, 'ready', AddNamespaceHandler);
chart.draw(data, options);
var exportsPie="return xepOnline.Formatter.Format('"+chartDivId+"', {render:'download', mimeType:'application/pdf', filename:'"+fileName+"'})";
var exportsPie1="return xepOnline.Formatter.Format('"+chartDivId+"', {render:'download', mimeType:'image/svg+xml', filename:'"+fileName+"'})";
jQuery('#export').html('Export To PDF Export To Image');
// Chart Table Data - Start
jQuery('#tables').html('<button class="click" style="font-family: Helvetica Neue,Helvetica,Arial,sans-serif; box-shadow: 0 0 0 0;" data-toggle="modal" data-target="#openModal" onclick="loadExportChartTable();">Table Data</button>');
var buttons="return xepOnline.Formatter.Format('parent_table', {render:'download',mimeType:'application/pdf', filename:'"+fileName+"'})";
jQuery('#buttons_table').html('<button onclick="'+ buttons +'">PDF</button> <button onclick="dataTableToCSV();">EXCEL</button>');
// Chart Table Data - End
}
// Load the Export Chart table data
function loadExportChartTable() {
var table_data = new google.visualization.Table(document.getElementById('table_div'));
google.visualization.events.addListener(table_data, 'ready', AddNamespaceHandler);
table_data.draw(data, {showRowNumber: false, width: '100%', height: '100%'});
}
function dataTableToCSV() {
var dataTable_arg = data;
var dt_cols = dataTable_arg.getNumberOfColumns();
var dt_rows = dataTable_arg.getNumberOfRows();
var csv_cols = [];
var csv_out;
for (var i=0; i<dt_cols; i++) {
csv_cols.push(dataTable_arg.getColumnLabel(i).replace(/,/g,""));
}
csv_out = csv_cols.join(",")+"\r\n";
for (i=0; i<dt_rows; i++) {
var raw_col = [];
for (var j=0; j<dt_cols; j++) {
raw_col.push(dataTable_arg.getFormattedValue(i, j, 'label').replace(/,/g,""));
}
csv_out += raw_col.join(",")+"\r\n";
}
//return csv_out;
this.downloadCSV(csv_out, fileName);
}
function downloadCSV (csv_out, fileName) {
var blob = new Blob([csv_out], {type: 'text/csv;charset=utf-8'});
var url = window.URL || window.webkitURL;
var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
link.href = url.createObjectURL(blob);
link.download = fileName+".csv";
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, true);
link.dispatchEvent(event);
}
</script>
I need same dropdown and "Table Data" button in all charts now I am getting only in first chart.
If anybody has any solution or idea to resolve this issue.
Please anybody can help me to get this? Thanks in advance.
Finally I got answer for my question.
drop down list and Table Data button both accepts static id that's why I able to get only in one chart.
For getting in other charts I made it dynamic added count variable in dashboardLayout.jsp foreach loop and added in param variable in each chart which declared in dashboardLayout.jsp file.
Code snippet is as below:
dashboardLayout.jsp
<div class="dropdown">
Export
<div class="dropdown-content" id="export${theCount.count}"></div>
</div>
<c:choose>
<c:when test="${chart.chartName eq 'columnbar'}">
<jsp:include page="chartsview/columnBarChart.jsp">
<jsp:param name="chartDivId" value="${chart.chartDivId}"/>
<jsp:param name="jsondata" value="${chart.merchantReportData.responseData}"/>
<jsp:param name="linkedJsonData" value="${chart.merchantReportData.responseLinkedData}"/>
<jsp:param name="xaxisLable" value="${chart.xAxisLable}"/>
<jsp:param name="yaxisLable" value="${chart.yAxisLable}"/>
<jsp:param name="exportParam" value="export${theCount.count}"/>
<jsp:param name="tablesParam" value="tables${theCount.count}"/>
</jsp:include>
<div class="portlet-content" id="${chart.chartDivId}"> ColumnBar Chart load here </div>
</c:when>
</c:choose>
columnBarChart.jsp
var exportDiv = null;
var tableDiv = null;
exportDiv = "${param.exportParam}";
tableDiv = "${param.tablesParam}";
jQuery('#'+exportDiv).html('Export To PDF Export To Image');
jQuery('#'+tableDiv).html('<button class="click" style="font-family: Helvetica Neue,Helvetica,Arial,sans-serif; box-shadow: 0 0 0 0;" data-toggle="modal" data-target="#openModal" onclick="loadExportChartTable();">Table Data</button>');
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 using highcharts to create a donut chart. The colours for each section are defined in the options passed via JS.
self.chartView = new Donut({
el: this,
colors: ['#96c6e3','#d8c395','#7fb299','#c693c3'],
data: $(this).data('series')
});
I would like to define these colours in CSS and then grab them for donut chart. Something along the lines of:
CSS
#color1{
background-color: #96c6e3;
}
JS
self.chartView = new Donut({
el: this,
colors: [$('#color1').css('background-color') ],
data: $(this).data('series')
});
But I'm not even sure this is possible.
For example, see this code snippet:
$(function() {
var colors = [
$('#color1').css('background-color'),
$('#color2').css('background-color')
];
$('#container').highcharts({
colors: colors,
series: [{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8]
]
}]
});
});
#color1 {
background-color: #96c6e3;
}
#color2 {
background-color: red;
}
#colors {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="colors">
<div id="color1"></div>
<div id="color2"></div>
</div>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>