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>
Related
I have Pie and Column charts from the same source data.
I want colors in bar chart to have the corrsponding colors like in Pie chart. These are default Google Charts colors (in order). So first column should be blue, second red, third yellow and fourth green. How to achieve this?
in a column chart, values in the same series are the same color by default
series are defined by columns, to have different colors by default,
place each value in a separate column
however, this presents a problem
if you structure the data as follows, then you lose the x-axis labels
you only have one label for all columns
var data = google.visualization.arrayToDataTable([
['x', 'y0', 'y1', 'y2', 'y3'],
['Razina0', 898, 37319, 8980, 35400]
]);
if you try the next approach, then the columns will not be spaced properly
there will be gaps for the null values
var data = google.visualization.arrayToDataTable([
['x', 'y0', 'y1', 'y2', 'y3'],
['Razina0', 898, null, null, null],
['Razina1', null, 37319, null, null],
['Razina2', null, null, 8980, null],
['Razina3', null, null, null, 35400],
]);
the best option is to use a style column
this will allow you to keep the current data structure
and provide different colors for each column
the only drawback is you have to provide the color
so you lose the default colors
as such, recommend drawing the pie chart first
then use the colors assigned to each slice
when the pie chart's 'ready' event fires
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['x', 'y0'],
['Razina0', 898],
['Razina1', 37319],
['Razina2', 8980],
['Razina3', 35400]
]);
var chartPie = new google.visualization.PieChart(document.getElementById('chart_pie'));
var chartColumn = new google.visualization.ColumnChart(document.getElementById('chart_column'));
google.visualization.events.addListener(chartPie, 'ready', function () {
var colIndex = data.addColumn({type: 'string', role: 'style'});
$.each($('#chart_pie path'), function (rowIndex) {
data.setValue(rowIndex, colIndex, $(this).attr('fill'));
});
chartColumn.draw(data, {
legend: {
position: 'none'
}
});
});
chartPie.draw(data, {
height: 240
});
}
div {
display: inline-block;
}
<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_pie"></div>
<div id="chart_column"></div>
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>
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>
I have to create a line chart, which has vertical bands in the background, and a vertical line at a specified position.Following is a sample chart image.
Sample chart
I tried to create a combo chart with line and bar as my series, to get the blue line and red vertical line. But i am unable to figure out how to get the vertical bands. Histogram is not supported by the combo chart. There is no option to create bar charts with variable width of each bar as well. Following is what i am able to create till now:
chart created so far
Following is my code:
function drawChart() {
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable([
['Percentile', 'Number of students', 'Vertical lines',{ role: 'style' }],
[1, 0.2020202,,''],
[3, 0.546875,,''],
[10, 1.20967742,,''],
[25, 1.87969925,,''],
[50, 1.953125, ,''],
[75, 1.32743363,,''],
[90, 0.64814815, ,''],
[97, 0.25316456, ,''],
[99, 0.00621891,,''],
[78, ,20,'stroke-width: 2; fill-color: red']
]);
var options = {
vAxis: {
gridlines:{count: 6},
viewWindow:{ max: 2.5}
},
hAxis: {
ticks: [0,20,40,60,80,100,120]
},
seriesType: 'line',
series: {1: {type: 'bars'}},
bar:{groupWidth:2},
intervals: { 'lineWidth':2, 'barWidth': 0.5, style: 'boxes' },
curveType: 'function',
legend: { position: 'none' },
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ComboChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
Please suggest how can these vertical bands be achieved?
I have a column chart as below image. I want to style excellent bar green since it is over the average, very good to blue and fair to red color. Is this possible ?
Based on the value of the bar/cell i want to change the background color for the Column Chart
Since all bars are colored by data series, you have to split your bars into different series in order to make them different colors. You can use calculated columns in a DataView to accomplish this:
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Value');
data.addRows([
['Foo', 2],
['Bar', 4],
['Baz', -3],
['Cud', 6],
['Waq', -8],
['Bat', -2],
['Cad', 5],
['Giv', 3],
['Muj', 9],
['Lof', -7],
['Duq', 5],
['Kaf', 1],
['Zij', 4]
]);
var view = new google.visualization.DataView(data);
// add as many different series as needed
// make sure all possible values are covered, so you don't have any gaps where a data point can't be assigned to a series
view.setColumns([0, {
type: 'number',
label: 'Value',
calc: function (dt, row) {
// if the value is less than 0, add to the red series
return (dt.getValue(row, 1) < 0) ? dt.getValue(row, 1) : null;
}
}, {
type: 'number',
label: 'Value',
calc: function (dt, row) {
// if the value is greater than or equal to 0, add to the green series
return (dt.getValue(row, 1) >= 0) ? dt.getValue(row, 1) : null;
}
}]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, {
legend: 'none',
isStacked: true,
height: 300,
width: 800,
// set the colors to use for the series (in the same order as the columns in the view)
colors: ['red', 'green']
/* or you can use the series.<series index>.color option to assign colors to specific series:
series: {
0: {
color: 'red'
},
1: {
color: 'green'
}
}
*/
});
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawChart});
See it working here: http://jsfiddle.net/asgallant/dMWWk/