I am using Google Donut Chart.
In my case, sometime I will have below data
{
DATA_1: 10,
DATA_2: 15,
INVALID_DATA: 10000000 (Big Number)
}
In such case, my valid data is showing very thin or slice not visible in Charts.
Is there any option in Google Charts to hide particular Slice to make visible other slices better?
I want valid data to show percentage with INVALID_DATA, but just hiding the INVALID_DATA Slice.
there are no options on the chart itself, but hiding a slice can be done with a DataView
but cannot avoid skewing the size of the remaining slices,
relative to the hidden slice
in the following example, a column is added to calculate the % with the hidden slice
then the option pieSliceText: 'value' is used to show the true %
a DataView is used to hide the original value column, and the row with the big slice
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Data Type', 'Value'],
['DATA_1', 10],
['DATA_2', 15],
['INVALID_DATA', 10000000]
]);
var options = {
pieHole: 0.4,
pieSliceText: 'value',
theme: 'maximized',
height: 262,
width: 262,
};
// get total -- sum
var dataGroup = google.visualization.data.group(
data,
[{column: 0, type: 'string', modifier: function () {return '';}}],
[{column: 1, type: 'number', aggregation: google.visualization.data.sum}]
);
var hideRows = [];
data.addColumn({type: 'number', label: '%'});
for (var i = 0; i < data.getNumberOfRows(); i++) {
// set % value
data.setValue(i, 2, data.getValue(i, 1) / dataGroup.getValue(0, 1));
// hide big #
if (data.getValue(i, 2) > .99) {
hideRows.push(i);
}
}
var numberFormat = new google.visualization.NumberFormat({
pattern: '#,##0.00000 %'
});
numberFormat.format(data, 2);
var dataView = new google.visualization.DataView(data);
dataView.hideColumns([1]);
dataView.hideRows(hideRows);
var pieChart = new google.visualization.PieChart(document.getElementById('pieChart_div'));
pieChart.draw(dataView, options);
var tableChart = new google.visualization.Table(document.getElementById('tableChart_div'));
tableChart.draw(data);
},
packages: ['corechart', 'table']
});
div {
padding: 2px 2px 2px 2px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="pieChart_div"></div>
<div id="tableChart_div"></div>
Related
I have a Google pie chart that I try to animate using simple JavaScript code.
I wish to change to colors of my pie slices. Why my code is not working?
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['A1', 0],
['Failed',1],
['A2', 0],
['Passed', 3],
]);
var colors1 = ['#ef7777', '#ef7777', '#b2d284', '#b2d284', '#f6c7b6'];
var colors2 = ['#ff00ff', '#ff00ff', '#02d2ff', '#02d2ff', '#f6c7b6'];
var colors3 = colors2;
var options1 = {'title':'Logic', 'width':'50%', 'height':'50%', legend:{position:'none'}, 'is3D':true,
chartArea: {width: '70%', height: '70%'},
colors: colors3,
'backgroundColor': '#fef7f8',
pieSliceTextStyle: {
color: '#000000',
bold: true,
fontSize:16
}
};
var chart1 = new google.visualization.PieChart(document.getElementById('piechart1'));
chart1.draw(data1, options1);
var percent = 0;
var handler = setInterval(function(){
// values increment
percent += 1;
if (percent%2 == 1) {
colors3 = colors1;
}
else
{
colors3 = colors2;
}
chart1.draw(data1, options1);
if (percent > 74)
clearInterval(handler);
}, 333);
}
So, I am setting here 2 arrays with color sets for my pie chart. The first have colors of red and green, the 2nd one have colors of blue and purple.
I wish to switch between these color sets continuously using the function "setInterval".
colors is a key of your options object. The callback function of your setInterval call changes a variable called colors3 but you don't assign it to the original object so it won't ever be used.
if (percent % 2 == 1) {
colors3 = colors1;
} else {
colors3 = colors2;
}
options1.colors = colors3; // here we're assigning it!
chart1.draw(data1, options1);
i am creating google charts and I already implement top 5 user column charts after that if you select first user column than displaying first user page history data from other variables(eachuser_data) its easy implement function in high charts! but in google charts, I don't know about add events.addListener work or not in this problem. let me know google charts provide click event on each column and display other graphs in same graph draw function. ? thank you in advance
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var charts = {};
var options = {
Column: {
chartArea: {
height: '100%',
width: '100%',
top: 24,
left: 64,
right: 32,
bottom: 48,
},
'vAxis': {
title: 'Cost in USD ($)', format:'$#',
},
height: '100%',
legend: {
position: 'bottom'
},
width: '100%'
}
};
// columns charts data
//top 5 user data with total click
var jsonData = [["johan",69],["jack",23],["scott",24],["x",5],["y",10]];
loadData(jsonData, '1', 'Column');
//specifc user data
var user1 = [["report1",45],["report2",40],["index.html",50]];
var user2 = [["report1",4],["report2",3],["index.html",5]];
var user3 = [["report1",4],["report2",3],["index.html",5]];
var user4 = [["report1",4],["report2",3],["index.html",5]];
var user5 = [["report1",4],["report2",3],["index.html",5]];
// load json data
function loadData(jsonData, id, chartType) {
// create data table
var dataTable = new google.visualization.DataTable();
// add date column
dataTable.addColumn('string', 'Total numbe of click');
var rowIndex = dataTable.addRow();
dataTable.setValue(rowIndex, 0, dataTable.getColumnLabel(0));
$.each(jsonData, function(productIndex, product) {
var colIndex = dataTable.addColumn('number', product[0]);
// add product data
dataTable.setValue(rowIndex, colIndex, product[1]);
});
// draw chart
$(window).resize(function () {
drawChart(id, dataTable);
});
drawChart(id, dataTable);
}
function drawChart(id, dataTable) {
if (!charts.hasOwnProperty(id)) {
charts[id] = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart-' + id,
options: {
vAxis: {
title: 'Cost in USD ($)',
format: '$#',
},
width: '100%',
height: '100%',
legend: {
position: 'bottom'
},
},
});
}
charts[id].setDataTable(dataTable);
charts[id].draw();
}
});
<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-1"></div>
to know which column has been clicked / selected,
listen for the 'select' event
google.visualization.events.addListener(chart, 'select', chartSelection);
then use chart method getSelection() to get the row and column index of the column selected
getSelection will return an array of objects
[{row: 0, column: 1}]
the select event will fire both when a column is selected and un-selected
be sure to check the length of the array return by getSelection()
before trying to access the array contents
for column charts, only one column can be selected at a time
so the values of the selection will always be the first element in the array
function chartSelection() {
var selection = chart.getSelection();
if (selection.length > 0) {
var row = selection[0].row;
var col = selection[0].column;
var xValue = data.getValue(row, 0);
var yValue = data.getValue(row, col);
console.log('selection: ' + xValue + ' = ' + yValue);
} else {
console.log('nothing selected');
}
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['x', 'y0', 'y1'],
['A', 6, 7],
['B', 7, 9],
['C', 8, 11],
['D', 9, 11],
['E', 5, 6]
]);
var options = {
legend: {
alignment: 'end',
position: 'top'
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'select', chartSelection);
function chartSelection() {
var selection = chart.getSelection();
if (selection.length > 0) {
var row = selection[0].row;
var col = selection[0].column;
var xValue = data.getValue(row, 0);
var yValue = data.getValue(row, col);
console.log('selection: ' + xValue + ' = ' + yValue);
} else {
console.log('nothing selected');
}
}
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I've created the below code example which is showing the sales quantity for two products I need to display the quantity value on each column please help..
<html>
<head>
<style>
#U{
margin: 0 auto;
width: 90%;
height: 500px;
color: black;
}
</style>
<meta charset="utf-8">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable({"cols":[{"label":"REPLACE DATE","type":"string"},{"label":"ITEM","type":"number"},{"label":"QUANTITY REPLACED","type":"number"}],"rows":[{"c":[{"v":"01\/29"},{"v":"IN-U-1"},{"v":11}]},{"c":[{"v":"01\/29"},{"v":"IN-U-1"},{"v":5}]},{"c":[{"v":"01\/30"},{"v":"IN-U-1"},{"v":136}]},{"c":[{"v":"01\/30"},{"v":"IN-U-2"},{"v":94}]},{"c":[{"v":"01\/31"},{"v":"IN-U-1"},{"v":130}]},{"c":[{"v":"01\/31"},{"v":"IN-U-2"},{"v":87}]},{"c":[{"v":"02\/01"},{"v":"IN-U-1"},{"v":127}]},{"c":[{"v":"02\/01"},{"v":"IN-U-2"},{"v":100}]},{"c":[{"v":"02\/02"},{"v":"IN-U-1"},{"v":114}]},{"c":[{"v":"02\/02"},{"v":"IN-U-2"},{"v":89}]},{"c":[{"v":"02\/03"},{"v":"IN-U-1"},{"v":131}]},{"c":[{"v":"02\/03"},{"v":"IN-U-2"},{"v":145}]},{"c":[{"v":"02\/04"},{"v":"IN-U-1"},{"v":142}]},{"c":[{"v":"02\/04"},{"v":"IN-U-2"},{"v":139}]},{"c":[{"v":"02\/05"},{"v":"IN-U-1"},{"v":12}]},{"c":[{"v":"02\/05"},{"v":"IN-U-2"},{"v":27}]},{"c":[{"v":"02\/06"},{"v":"IN-U-1"},{"v":146}]},{"c":[{"v":"02\/06"},{"v":"IN-U-2"},{"v":99}]},{"c":[{"v":"02\/07"},{"v":"IN-U-1"},{"v":219}]},{"c":[{"v":"02\/07"},{"v":"IN-U-2"},{"v":171}]}]});
var options = {
title: 'Sales',
vAxis: {title: "Quantity", gridlines: { count: 6 }},
hAxis: {title: "Per Day"},
//is3D: 'true',
chartArea: {'top': '30','left':'100'},
bar: { groupWidth: "80%" },
//annotations.alwaysOutside: true,
backgroundColor: "transparent"
};
/* pivot the data table
* set column A as the first column in the view,
* then we have to separate out the C values into their own columns
* according to the value of B, using a DataView with calculated columns
*/
// get all the values in column B
// this sorts the values in lexicographic order, so if you need a different order you have to build the array appropriately
var distinctValues = data.getDistinctValues(1);
var viewColumns = [0];
var groupColumns = [];
// build column arrays for the view and grouping
for (var i = 0; i < distinctValues.length; i++) {
viewColumns.push({
type: 'number',
label: distinctValues[i],
calc: (function (x) {
return function (dt, row) {
// return values of C only for the rows where B = distinctValues[i] (passed into the closure via x)
return (dt.getValue(row, 1) == x) ? dt.getValue(row, 2) : null;
}
})(distinctValues[i])
});
groupColumns.push({
column: i + 1,
type: 'number',
label: distinctValues[i],
aggregation: google.visualization.data.sum
});
}
var view = new google.visualization.DataView(data);
view.setColumns(viewColumns);
// next, we group the view on column A, which gets us the pivoted data
var pivotedData = google.visualization.data.group(view, [0], groupColumns);
var chart = new google.visualization.ColumnChart(document.getElementById('U'));
chart.draw(pivotedData, options, {});
}
</script>
</head>
<body>
<div id="U"></div>
</body>
</html>
Please help...
Thanks in advance,
Best regards,
Hisham
See Labeling Bars...
Basically, just add another view column for the annotation...
{
calc: 'stringify',
sourceColumn: 1, // identify column value to be displayed
type: 'string',
role: 'annotation'
}
In this case, you may need to create another view off of pivotedData
I'm having trouble scaling my chart correctly. My chart represents data for every hour of the day in a 24 hour format, meaning that I need the numbers 0-24 on my linechart.
I've tried adding the logScale, minValue and maxValue properties to the hAxis, but nothing is working.
As you can see on the chart, the hour axis is not spanning a fixed axis from 0-24 hours, but instead from 9-15 hours.
I also only have 3 rows in my data set, which reside on the hours 9, 14 and 15. Despite this, the lines are spanning from 9-14 as if they have values; however there is no data there, so the lines should be running along the bottom at 0 between these two points.
How can I put a fixed horizontal scale on my chart, and have individual values on my lines for each hour?
Here's my code:
google.load('visualization', '1.1', {packages: ['line']});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var json = $.getJSON('my JSON data link', function(data)
{
var chartStructure = new google.visualization.DataTable();
var chartData = [];
chartStructure.addColumn('number', 'Hour');
chartStructure.addColumn('number', 'Pageviews');
chartStructure.addColumn('number', 'Unique Pageviews');
chartStructure.addColumn('number', 'Sales');
chartStructure.addColumn('number', 'Earnings in $AUD');
for (i = 0; i < data.length; i++)
{
chartData[i] = [];
chartData[i][0] = parseInt(data[i].hour);
chartData[i][1] = parseFloat(data[i].profit);
chartData[i][2] = parseFloat(data[i].profit);
chartData[i][3] = parseFloat(data[i].sales);
chartData[i][4] = parseFloat(data[i].profit);
// These chartData values are not correct because I am testing
chartStructure.addRows(chartData);
}
var options = {
hAxis: {
'minValue': 0,
'maxValue': 24
}
};
var chart = new google.charts.Line(document.getElementById('todays-total-sales'));
chart.draw(chartStructure, options);
});
}
$(window).resize(function()
{
drawChart();
});
Use viewWindow.
hAxis: {
title: 'Time',
viewWindow:{
max:1000,
min:-100
}
},
JSFiddle
UPDATE
If you are using MaterialCharts please note that the options have different syntax!
In order for you to be able to use the classic options, you need to change
chart.draw(data, options);
to
chart.draw(data, google.charts.Line.convertOptions(options));
HERE is your updated fiddle.
var options = {
title: "Posted Memes",
width: 450,
height: 300,
is3D:true,
bar: { groupWidth: "95%" },
legend: { position: "none" },
vAxis: {
title: 'No of Memes',
viewWindowMode: 'explicit',
viewWindow: {
max: 180,
min: 0,
interval: 1,
},
}
};
I'm using Google line chart in my project which displays different lines according to data. I want to show/hide lines when clicking their legend.
function drawSalesGraph()
{
if (sales_data_graph.length > 1)
{
graph_height = 500;
var options_graph = {
width: '1200',
height:graph_height,
colors: ['#ea6f09','#fb250d', '#0ac9c6', '#2680be', '#575bee','#6bd962','#ff0000','#000000'],
fontSize : 10,
pointSize : 10,
legend: {'position': 'right'}
};
var data = new google.visualization.arrayToDataTable(sales_data_graph);
$('#graph_sales_data').show();
}
else
{
var data = new google.visualization.DataTable();
$('#graph_sales_data').hide();
}
// Create and draw the visualization.
chart = new google.visualization.AreaChart(document.getElementById('graph_sales_data'));
chart.draw(data, options_graph);
}
I found some simple solution for this issue, so I'm sharing the code here
It's a trick using 'lineDashStyle' property of series option :)
Set the first value of lineDashStyle as 0, and second as something that greater than 0
( Google Chart Version is 45 )
... prepare the data and option for chart
// draw chart
chart.draw(data, option);
// add event handler for legend click
google.visualization.events.addListener(chart, 'click', function (e) {
var legendPrefix = 'legendentry#';
// Check if clicked legend entry
if (e.targetID.indexOf(legendPrefix) == 0) {
// index of clicked legend entry
var idx = e.targetID.substring(legendPrefix.length);
// Show line
if (option.series[idx].lineDashStyle && option.series[idx].lineDashStyle[0] == 0) {
option.series[idx].lineDashStyle = option.series[idx].originalLineDashStyle;
}
// Hide line
// ( Set the first value of lineDashStyle as 0,
// and second as something that greater than 0 )
else {
option.series[idx].originalLineDashStyle = option.series[idx].lineDashStyle;
option.series[idx].lineDashStyle = [0, 1];
}
chart.draw(data, option);
}
});
use this
vAxis: {
ridlines: {
color: 'transparent'
},
baselineColor: 'transparent'
},
Read this Answer as well or jsfiddle preview
This is how I solved my issue to hide/display line when clicked on its respective legend title.
/*****drawChart is used to Draw Graph.******/
function drawChart() {
if (sales_data_graph.length > 1)
{
$('#graph_sales_data').show();
var data = new google.visualization.arrayToDataTable(sales_data_graph);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'graph_sales_data',
dataTable: data,
colors: ['#ea6f09', '#fb250d', '#0ac9c6', '#2680be', '#575bee', '#6bd962', '#ff0000', '#000000'],
options: {
width: 1200,
height: 500,
fontSize: 10,
pointSize: 10
}
});
// create columns array
var columns = [0];
/* the series map is an array of data series
* "column" is the index of the data column to use for the series
* "roleColumns" is an array of column indices corresponding to columns with roles that are associated with this data series
* "display" is a boolean, set to true to make the series visible on the initial draw
*/
var seriesMap = [{
column: 1,
roleColumns: [1],
display: true
}, {
column: 2,
roleColumns: [2],
display: true
}, {
column: 3,
roleColumns: [3],
display: true
}, {
column: 4,
roleColumns: [4],
display: true
}, {
column: 5,
roleColumns: [5],
display: true
}, {
column: 6,
roleColumns: [6],
display: true
}, {
column: 7,
roleColumns: [7],
display: true
}, {
column: 8,
roleColumns: [8],
display: true
}];
var columnsMap = {};
var series = [];
for (var i = 0; i < seriesMap.length; i++) {
var col = seriesMap[i].column;
columnsMap[col] = i;
// set the default series option
series[i] = {};
if (seriesMap[i].display) {
// if the column is the domain column or in the default list, display the series
columns.push(col);
}
else {
// otherwise, hide it
columns.push({
label: data.getColumnLabel(col),
type: data.getColumnType(col),
sourceColumn: col,
calc: function() {
return null;
}
});
// backup the default color (if set)
if (typeof(series[i].color) !== 'undefined') {
series[i].backupColor = series[i].color;
}
series[i].color = '#CCCCCC';
}
for (var j = 0; j < seriesMap[i].roleColumns.length; j++) {
//columns.push(seriesMap[i].roleColumns[j]);
}
}
chart.setOption('series', series);
function showHideSeries() {
var sel = chart.getChart().getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (sel[0].row == null) {
var col = sel[0].column;
if (typeof(columns[col]) == 'number') {
var src = columns[col];
// hide the data series
columns[col] = {
label: data.getColumnLabel(src),
type: data.getColumnType(src),
sourceColumn: src,
calc: function() {
return null;
}
};
// grey out the legend entry
series[columnsMap[src]].color = '#CCCCCC';
}
else {
var src = columns[col].sourceColumn;
// show the data series
columns[col] = src;
series[columnsMap[src]].color = null;
}
var view = chart.getView() || {};
view.columns = columns;
chart.setView(view);
chart.draw();
}
}
}
google.visualization.events.addListener(chart, 'select', showHideSeries);
// create a view with the default columns
var view = {
columns: columns
};
chart.draw();
}
else
{
$('#graph_sales_data').hide();
}
}