How to add html in rows of google chart API - charts

I have a chart with values like below one column have multiple values with forward slash.
but i want to change it like this image.
Here is my chart code
while(start<=end)
{
orgcode=org_hi.substring(start,org_hi.indexOf('-',start));
/* code add by sim*/
/* var res = orgcode.split("/");
if(res.length!=0)
{
var i = 0;
res.forEach(function(entry) {
var sim = "[{v:'"+entry+"', f:'"+entry+"<div style='color:red; font-style:italic'>President</div>'},'', 'The President']";
extndOrg.push(sim);
i++;
});
}*/
/* end code*/
/* if(res.length!=0)
{
var arr1d=new Array(extndOrg,orghead);
}
else
{
var arr1d=new Array(orgcode,orghead);
}*/
var arr1d=new Array(orgcode,orghead);
arr2d.push(arr1d);
start=start+orgcode.length+1;
}
}
var data = new google.visualization.DataTable();
data.addColumn('string', 'Node');
data.addColumn('string', 'Parent');
data.addRows(arr2d);
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
// chart.draw(data);
chart.draw(data, {allowHtml:true});
and orgcode have a dynamic value which is splited with '-'
here is that dynamic value
XPHNG/XPHNG-DDPOA/XPHNG/DDPOA-RUDCP/XPHNG/DDPOA/RUDCP-DCCBA-XENMD-EEPD2/XPHNG/DDPOA/RUDCP/DCCBA/XENMD/EEPD2-DICAM-ZSBAM/XPHNG/DDPOA/RUDCP/DCCBA/XENMD/EEPD2/DICAM/ZSBAM-ARCS8/XPHNG/DDPOA/RUDCP/DCCBA/XENMD/EEPD2/DICAM/ZSBAM/ARCS8-GMHRA-WAKFA-DTPMB/XPHNG/DDPOA/RUDCP/DCCBA/XENMD/EEPD2/DICAM/ZSBAM/ARCS8/GMHRA/WAKFA/DTPMB

in order to use html on the nodes...
1) need to set the following option...
allowHtml: true
e.g.
chart.draw(data, {
allowHtml: true
});
2) need to use object notation for the cell values
where v: is the value, and f: is the formatted value, e.g.
{v: 'Mike', f: '<div>Email Mike</div>'}
the chart will use the value as the id for building the relationships
but display the formatted value on the node
if you don't want to provide object notation,
you can also use the setFormattedValue method on the data table
data.setFormattedValue(1, 0, namesHtml);
3) see following working snippet...
object notation is used to provide link for 'Mike'
'Jim' is later updated with the split string using the method setFormattedValue
google.charts.load('current', {
callback: drawChart,
packages: ['orgchart']
});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addRows([
[{v: 'Mike', f: '<div>Email Mike</div>'}, ''],
['Jim', 'Mike'],
['Alice', 'Mike'],
['Bob', ''],
['Carol', 'Bob']
]);
var splitStr = 'XPHNG/XPHNG-DDPOA/XPHNG/DDPOA-RUDCP/XPHNG/DDPOA/RUDCP-DCCBA-XENMD-EEPD2/XPHNG/DDPOA/RUDCP/DCCBA/XENMD/EEPD2-DICAM-ZSBAM/XPHNG/DDPOA/RUDCP/DCCBA/XENMD/EEPD2/DICAM/ZSBAM-ARCS8/XPHNG/DDPOA/RUDCP/DCCBA/XENMD/EEPD2/DICAM/ZSBAM/ARCS8-GMHRA-WAKFA-DTPMB/XPHNG/DDPOA/RUDCP/DCCBA/XENMD/EEPD2/DICAM/ZSBAM/ARCS8/GMHRA/WAKFA/DTPMB';
var names = splitStr.split('-');
var namesHtml = '';
names.forEach(function (name) {
namesHtml += '<div>' + name + '</div>'
});
// change Jim
data.setFormattedValue(1, 0, namesHtml);
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data, {
allowHtml: true
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

Google ScatterChart from uploaded csv file

How can plot a Google Scatterchartfrom an uploaded csv file?
It is showing a blank page.
I tried the following code:
Loading the scripts:
<script src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
Then I got this part from an example:
<script> // wait till the DOM is loaded
$(function() {
// grab the CSV
$.get("https://www.batemo.de/wp-content/uploads/general/data_chart_gravimetric.csv", function(csvString) {
// display the contents of the CSV
$("#chart").html(csvString); }); });
// load the visualization library from Google and set a listener
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("https://www.batemo.de/wp-content/uploads/general/data_chart_gravimetric.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data); view.setColumns([0,1]);
var options = {};
var chart = new google.visualization.ScatterChart(document.getElementById('chart'));
chart.draw(view, options);
}); }
</script>
the example has an error.
the brackets at the end of the following line...
$("#chart").html(csvString); }); }); <-- these two sets of brackets
need to move down below the rest of the code,
here is the full, corrected snippet...
$(function() {
// grab the CSV
$.get("https://www.batemo.de/wp-content/uploads/general/data_chart_gravimetric.csv", function(csvString) {
// display the contents of the CSV
$("#chart").html(csvString);
// load the visualization library from Google and set a listener
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("https://www.batemo.de/wp-content/uploads/general/data_chart_gravimetric.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data); view.setColumns([0,1]);
var options = {};
var chart = new google.visualization.ScatterChart(document.getElementById('chart'));
chart.draw(view, options);
}); }
}); });

Google Visualization - Set Pie Chart Slice Color

I have a data table that is used for a pie chart and I need to set colors of slices based on a value in a row. For example, I have a table of car sales by type (e.g. lease, cash, finance) and I want to specify a color for each one. In the documentation, it seems possible to do this with bar charts, but I can't seem to do it with slices. I tried the following:
var pieChart = new google.visualization.ChartWrapper({
options : {
...
slices: [{color: 'black'}, {color: 'green'}, {color: 'red'}]
}
});
The colors get rendered but I want to specify black for lease. Any ideas on how I can get this to work?
the colors in the slices array should be in the same order as the rows in the data table
so, with the following rows...
data.addRows([
['Cash', 5],
['Finance', 20],
['Lease', 15]
]);
for 'Lease' to black, it should be the last color in the array
slices: [{color: 'green'}, {color: 'red'}, {color: 'black'}]
if the order of the rows is unknown, you could set the colors dynamically
use an object to create a map for the colors
// create color map
var colors = {
'Cash': 'green',
'Finance': 'red',
'Lease': 'black'
};
then build the slices array based on the values in the data table
// build slices
var slices = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
slices.push({
color: colors[data.getValue(i, 0)]
});
}
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'sales');
data.addColumn('number', 'count');
data.addRows([
['Cash', 5],
['Finance', 20],
['Lease', 15]
]);
data.sort([{column: 1, desc: true}]);
// create color map
var colors = {
'Cash': 'green',
'Finance': 'red',
'Lease': 'black'
};
// build slices
var slices = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
slices.push({
color: colors[data.getValue(i, 0)]
});
}
var container = document.getElementById('chart_div');
var chart = new google.visualization.PieChart(container);
chart.draw(data, {
slices: slices
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Charts - HTML axis label and title

So I am trying to make html axis labels in google charts. However there does not seem to be any support for creating the axis labels or the title as HTML objects. The title is easy enough to fix, just add it in as a separate HTML object to the page, but the axis labels are more challenging. Has anyone been able to do this? As an example the below jsfiddle should show what happens when you attempt to use simple sub and sup html tags.
https://jsfiddle.net/jqmya8j9/1/
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(function () {
var data = [['X','Y']], i, options,
chart, dataTable;
for (i = 0; i < 20; i += 1) {
data.push([i, i * i]);
}
dataTable =
google.visualization.arrayToDataTable(data);
options = {
legend: 'none',
title: 'X<sub>m</sub> versus X<sup>2</sup>',
//best guess, does nothing
titleTextStyle: {isHtml: true},
hAxis: {title: 'X<sub>m</sub>'},
vAxis: {title: 'X<sup>2</sup>'}
};
chart = new
google.visualization.ScatterChart(document.body);
chart.draw(dataTable, options);
});
Based on the below answer (Thanks!), and what I am actually doing, I wrote the following general rule for this using _{} and ^{} instead of < sub > and < sup >
https://jsfiddle.net/jqmya8j9/2/
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(function () {
var data = [['X','Y']], i, options,
chart, dataTable;
for (i = 0; i < 20; i += 1) {
data.push([i, i * i]);
}
dataTable =
google.visualization.arrayToDataTable(data);
options = {
legend: 'none',
title: 'X_{m} versus X^2',
hAxis: {title: 'X_m'},
vAxis: {title: 'X^{2}'}
};
chart = new
google.visualization.ScatterChart(document.body);
google.visualization.events.addListener(chart, 'ready', function () {
$.each($('text'), function (index, label) {
var labelText = $(label).text();
if (labelText.match(/_|\^/)) {
labelText = labelText.replace(/_([^\{])|_\{([^\}]*)\}/g, '<tspan style="font-size: smaller;" baseline-shift="sub">$1$2</tspan>')
labelText = labelText.replace(/\^([^\{])|\^\{([^\}]*)\}/g, '<tspan style="font-size: smaller;" baseline-shift="super">$1$2</tspan>')
$(label).html(labelText);
}
});
});
chart.draw(dataTable, options);
});
the labels will only accept text...
the chart is drawn with svg, which can be changed manually when the 'ready' event fires
the labels will be <text> elements
to change the font style inline, use svg <tspan> elements within <text>
e.g.
<text>X<tspan baseline-shift="super">m</tspan></text>
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = [['X','Y']], i, options,
chart, dataTable;
for (i = 0; i < 20; i += 1) {
data.push([i, i * i]);
}
dataTable = google.visualization.arrayToDataTable(data);
options = {
legend: 'none',
title: 'Xm versus X2',
hAxis: {title: 'Xm'},
vAxis: {title: 'X2'}
};
chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
$.each($('text'), function (index, label) {
var labelText = $(label).text();
if (labelText.indexOf('X') > -1) {
labelText = labelText.replace(new RegExp(/m/g), '<tspan baseline-shift="super">m</tspan>');
labelText = labelText.replace(new RegExp(/2/g), '<tspan baseline-shift="super">2</tspan>');
$(label).html(labelText);
}
});
});
chart.draw(dataTable, options);
},
packages: ['corechart']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How to prevent Google Charts from changing x-axis order?

I'm trying to draw a Google Chart whose x-axis represents the week numbers. As we're crossing a new year, the axis goes 50, 51, 52, 1, 2, 3, ....
I'm properly ordering my data, but Google Charts insists on reordering my x-axis, and I end up with a weird graph:
var chartData = [
["Week","Revenue"],
[40,227],
[41,317],
[42,320],
[43,482],
[44,418],
[45,345],
[46,313],
[47,316],
[48,380],
[49,467],
[50,349],
[51,256],
[52,393],
[1,276],
[2,349],
[3,312]
];
google.load("visualization", "1", {
packages:["corechart"],
callback: function() {
var div = document.getElementById('chart');
var chartDataTable = google.visualization.arrayToDataTable(chartData);
var chart = new google.visualization['LineChart'](div);
chart.draw(chartDataTable);
}});
<div id="chart" style="height: 400px;">test</div>
<script src="//www.google.com/jsapi"></script>
How can I prevent it from reordering my data?
google's object notation allows you to provide a value (v:) and a formatted value (f:)
thus, you can use a value of 1 with a format of '40'
e.g. --> {v: 1, f: '40'}
in a row --> [{v: 1, f: '40'},227]
the following working snippet uses object notation to re-format the values for the x-axis,
and re-use those values for the x-axis labels (hAxis.ticks)
var chartData = [
["Week","Revenue"],
[40,227],
[41,317],
[42,320],
[43,482],
[44,418],
[45,345],
[46,313],
[47,316],
[48,380],
[49,467],
[50,349],
[51,256],
[52,393],
[1,276],
[2,349],
[3,312]
];
var hAxisTicks = [];
chartData.forEach(function (row, index) {
if (index === 0) {
return;
}
row[0] = {
v: index,
f: row[0].toString()
};
hAxisTicks.push(row[0]);
});
google.charts.load('current', {
callback: function () {
var div = document.getElementById('chart');
var chartDataTable = google.visualization.arrayToDataTable(chartData);
var chart = new google.visualization['LineChart'](div);
chart.draw(chartDataTable, {
hAxis: {
ticks: hAxisTicks
}
});
},
packages:['corechart']
});
<div id="chart"></div>
<script src="https://www.gstatic.com/charts/loader.js"></script>
note:
recommend using loader.js to load the the library, instead of jsapi
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
this only changes the load statement, see snippet above...
EDIT:
there are more options available for continuous axis
which must be sorted, or in reverse sort order ('number', 'date' values)
but the chart will respect the original sort order for a discrete axis ('string' values)
see following snippet for 'string' values
and discrete vs. continuous for more...
var chartData = [
["Week","Revenue"],
[40,227],
[41,317],
[42,320],
[43,482],
[44,418],
[45,345],
[46,313],
[47,316],
[48,380],
[49,467],
[50,349],
[51,256],
[52,393],
[1,276],
[2,349],
[3,312]
];
chartData.forEach(function (row, index) {
if (index === 0) {
return;
}
row[0] = row[0].toString();
});
google.charts.load('current', {
callback: function () {
var div = document.getElementById('chart');
var chartDataTable = google.visualization.arrayToDataTable(chartData);
var chart = new google.visualization['LineChart'](div);
chart.draw(chartDataTable);
},
packages:['corechart']
});
<div id="chart"></div>
<script src="https://www.gstatic.com/charts/loader.js"></script>

Google Charts: Horizontal Reference Line on Barchart

Having a Barchart like the following
I want to be able to draw an horizontal reference line (For example at 80%). However this doesn't seem to be possible on Google Charts.
I've tried several things, including combo charts with multiple series.
However it won't look very nice since the hAxis is discrete :(
Your help would be very appreciated.
add another series for the Reference Line
use the same value for all rows and change the series type to 'line'
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Category', 'Value', 'Reference'],
['Quant', 0.10, 0.80],
['Verbal', 0.30, 0.80],
['Total', 0.20, 0.80]
]);
var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(chartDiv);
chart.draw(data, {
colors: ['lime', 'magenta'],
legend: 'none',
series: {
1: {
type: 'line'
}
},
title: 'Percentile Score',
vAxis: {
format: 'percent',
viewWindow: {
min: 0,
max: 1
}
}
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
in the above snippet, the reference line stops at the center of the first and last columns
extend the line to the edges of the columns by changing the coordinates of the reference line,
use the 'ready' listener to know when the chart has been drawn
the key is finding the specific chart elements you need to work with,
in the following snippet, the series color is used to find the columns and reference line
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Category', 'Value', 'Reference'],
['Quant', 0.10, 0.80],
['Verbal', 0.30, 0.80],
['Total', 0.20, 0.80]
]);
var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(chartDiv);
// use colors to find chart elements
var colorMagenta = '#ff00ff';
var colorLime = '#00ff00';
var xBeg; // save first x coord
var xWidth; // save width of column
var rowIndex = -1; // find first column
google.visualization.events.addListener(chart, 'ready', function () {
// columns
Array.prototype.forEach.call(chartDiv.getElementsByTagName('rect'), function(rect, index) {
if (rect.getAttribute('fill') === colorLime) {
rowIndex++;
xWidth = parseFloat(rect.getAttribute('width')) / 2;
if (rowIndex === 0) {
xBeg = parseFloat(rect.getAttribute('x'));
}
}
});
// reference line
Array.prototype.forEach.call(chartDiv.getElementsByTagName('path'), function(path, index) {
if (path.getAttribute('stroke') === colorMagenta) {
// change line coords
var refCoords = path.getAttribute('d').split(',');
refCoords[0] = 'M' + xBeg;
var refWidth = refCoords[2].split('L');
refWidth[1] = parseFloat(refWidth[1]) + xWidth;
refCoords[2] = refWidth.join('L');
path.setAttribute('d', refCoords.join(','));
}
});
});
chart.draw(data, {
colors: [colorLime, colorMagenta],
legend: 'none',
series: {
1: {
type: 'line'
}
},
title: 'Percentile Score',
vAxis: {
format: 'percent',
viewWindow: {
min: 0,
max: 1
}
}
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>