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>
Related
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>
I want to remove y-axis values, I just want 0 and 1 once, but there are multiple 1's.
"gridlines: { count: 2}, " is not applying. Is there any solution for this?
the chart is using numbers for the y-axis that have decimal places,
which obviously aren't shown due to the number format
would need to see code, options used on the chart, etc. to understand why
also, drawing the chart before it's container is visible can cause problems
however, the chart in the image appears to be a Material chart
unfortunately, many of the options you could use to correct the issue
are not supported by Material charts, including...
{hAxis,vAxis,hAxes.*,vAxes.*}.gridlines.count
see --> Tracking Issue for Material Chart Feature Parity
recommend using Core chart instead, with following option...
theme: 'material'
using ticks will guarantee which labels appear...
vAxis: {
ticks: [0, 1]
},
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Category', 'Count'],
['Customers Added', 1.4],
['Posts Created', null],
['Cash Transaction', null],
['Card Transaction', null],
['Buy Incomplete', null],
['Merchant SignUp', null]
]);
var container = document.getElementById('chart_div');
var chartCol = new google.visualization.ColumnChart(container);
chartCol.draw(data, {
vAxis: {
ticks: [0, 1]
},
height: 400,
theme: 'material',
title: 'Agent Report'
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note:
Material --> google.charts.Bar -- packages: ['bar']
Core --> google.visualization.ColumnChart -- packages: ['corechart']
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?
Using {role: 'style'} I can apply different colors to a single series bar chart. But if I use the new Google "Material" barcharts, I can't.
"regular" Google charts (works):
google.load("visualization", '1.1', {packages:['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', {role: 'style'} ],
['Copper', 8.94, 'color: #FF9900'],
['Silver', 10.49,'color: #109618'],
['Gold', 19.30,'color: #3B3EAC'],
['Platinum', 21.45,'color: #0099C6']
]);
var view = new google.visualization.DataView(data);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: '85%'},
legend: { position: 'none' },
};
var chart = new google.visualization.ColumnChart(document.getElementById('barchart_values'));
chart.draw(view, options);
}
Same chart but using Google "Material" bar chart (different colors are not applied)
google.load("visualization", "1.1", {packages:["bar"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' } ],
['Copper', 8.94, 'color: #FF9900'],
['Silver', 10.49,'color: #109618'],
['Gold', 19.30,'color: #3B3EAC'],
['Platinum', 21.45,'color: #0099C6']
]);
var view = new google.visualization.DataView(data);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: '95%'},
legend: { position: 'none' },
};
options = google.charts.Bar.convertOptions(options);
var chart = new google.charts.Bar(document.getElementById('barchart_values'));
chart.draw(view, options);
}
It really seems impossible. There is no clou anywhere for Material Charts using individual colors, and if you set a color array the old way, like colors: [...] the Material Chart just adopt the first color and add this to all the bars. I believe this is not implemented in Material Charts at all (yet?).
But if you really want to colorize the bars, you can do it by code :
function colorize() {
var colors = ['#FF9900', '#109618', '#3B3EAC', '#0099C6'],
svg = document.getElementById('barchart_values').querySelector('svg'),
bars = svg.querySelectorAll('path');
for (var i=0;i<bars.length;i++) {
if (i !== selected) bars[i].setAttribute('fill', colors[i]);
}
}
colors[] are the colors from your data DataTable above. It is safe just to target <path>'s, since the paths that visualizes the bars are the only one present inside the <svg>.
This function can be triggered by the ready event :
google.visualization.events.addListener(chart, 'ready', colorize);
Since the chart is continuously redrawn upon select and onmouseover, attach listeners to those events too :
google.visualization.events.addListener(chart, 'select', colorize);
google.visualization.events.addListener(chart, 'onmouseover', colorize);
and let the user be able to select a bar, i.e dont redraw a selected bar :
function colorize() {
var colors = ['#FF9900', '#109618', '#3B3EAC', '#0099C6'],
selection = chart.getSelection(),
selected = selection[0] ? selection[0].row : -1,
svg = document.getElementById('barchart_values').querySelector('svg'),
bars = svg.querySelectorAll('path');
for (var i=0;i<bars.length;i++) {
if (i !== selected) bars[i].setAttribute('fill', colors[i]);
}
}
your Material Chart added with the code from above -> http://jsfiddle.net/o00oayvu/
This one helps me out
var tmpColors = new Array(['orange'],['purple'],['red'],['green']);
loop{
.....
.....
options.colors = tmpColors[i];
....
....
}
I'm generating some Google Charts and I'm stuck here. Google allows you to have your columns stacked. But it's either limited or I can't configure it to work. Taken from Google, here is an example showing number of cups of coffee produced in each year for two countries:
Say I have another data set for the same two countries, but this time I have instant coffee instead of ground. Example:
What I'd like to do is to stack these two datasets on top of each other. So each column would be a single country, but two divisions: bean and instant coffee.
I was thinking if there was a way of formatting the data table in the following way:
['Year', 'Austria', 'Austria (instant)', 'Bulgaria', 'Bulgaria (instant')],
['2003', 1736060, 10051, 250361, 68564],
['2004', 1338156, 65161, 786849, 1854654],
['2005', 1276579, 65451, 120514, 654654]
to generate something like
Your help is appreciated.
I just ran into this same issue today and followed your submission link. It seems that just recently someone replied with this:
"This is actually possible with the new Material Bar chart (albeit in
a somewhat roundabout way). In the new chart, if you make a chart
stacked, but place some series on a different axis, that creates a
separate stack for those series. Unfortunately, there is currently no
way to completely hide an axis yet, and you will have to explicitly
set the view window. Eventually we will introduce options to hide axes
and to align view windows, but this will have to do for now."
This fiddle seemed to help me solve this problem: http://jsfiddle.net/p7o0pjgg/
Here's the code:
google.load('visualization', '1.1', {
'packages': ['bar']
});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Nescafe Instant');
data.addColumn('number', 'Folgers Instant');
data.addColumn('number', 'Nescafe Beans');
data.addColumn('number', 'Folgers Beans');
data.addRows([
['2001', 321, 621, 816, 319],
['2002', 163, 231, 539, 594],
['2003', 125, 819, 123, 578],
['2004', 197, 536, 613, 298]
]);
// Set chart options
var options = {
isStacked: true,
width: 800,
height: 600,
chart: {
title: 'Year-by-year coffee consumption',
subtitle: 'This data is not real'
},
vAxis: {
viewWindow: {
min: 0,
max: 1000
}
},
series: {
2: {
targetAxisIndex: 1
},
3: {
targetAxisIndex: 1
}
}
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
};
You can do it using a stacked column chart, where all data series of one group (e.g. ground coffee) is on the left axis, and all data series of the other group on the right axis (instant coffee).
data and stacked column chart set-up
series of group 2 moved to right axis
The Visualization API does not support creating multiple column stacks per row of data. You can make a feature request to add support for this if you want.
The answer by Dan Hogan worked for me. However, the JSFiddle example didn't seem to work (not sure, why.) Here is a version that works for me.
google.charts.load('current', {'packages': ['bar']});
google.charts.setOnLoadCallback(function() {
$('.service-usage-graph').each(function() {
var table = new google.visualization.DataTable();
table.addColumn('string', 'Date');
table.addColumn('number', 'UL Peak');
table.addColumn('number', 'UL Off-peak');
table.addColumn('number', 'DL Peak');
table.addColumn('number', 'DL Off-peak');
table.addRow(['2001-01-01', 1, 2, 3, 4]);
table.addRow(['2001-01-03', 3, 2, 4, 2]);
table.addRow(['2001-01-04', 2, 2, 4, 2]);
table.addRow(['2001-01-05', 0, 1, 4, 5]);
table.addRow(['2001-01-06', 9, 2, 6, 8]);
table.addRow(['2001-01-07', 2, 2, 7, 3]);
var chart = new google.charts.Bar(this);
var options = google.charts.Bar.convertOptions({
isStacked: true,
series: {
2: { targetAxisIndex: 1 },
3: { targetAxisIndex: 1 }
},
vAxis: {
viewWindow: {
max: 15,
}
}
});
chart.draw(table, options);
});
});
<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 class="service-usage-graph"></div>