Google Chart Add Color Specific - html

How are you?
How do I force the color? I do not want them to be random. I read the documentation, but something is wrong. I can not tell. They help me? Thank you very much!
For Example: I want the Womens records in Black and the mens in Green.
Regarts!
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([
['status', 'number',{ role: 'style' },{ role: 'annotation' } ],
["Men", 5, '#b87333','M'],
["Girl", 7, '#0000FF','G'],
]);
var options = {
title: 'Sex',
is3D:true,
pieHole: 0.4,
//colors: ['#5cb85c','#f0ad4e']
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript"> </script>
<!--Div that will hold the pie chart-->
<div id="piechart"></div>

the only role supported by PieChart is 'tooltip'
both 'style' and 'annotation' are not supported
you can either use the colors configuration option,
colors: ['#5cb85c','#000000']
or the slices option...
slices: [{color: '#5cb85c'}, {color: '#000000'}]
in both options above, the first color in the array will be applied to the first row in the data table,
the second color, the second row, etc...
if you're not sure in which order the data will be,
you can use an object to map the values to a specific color
here, we build the array of colors, by matching the values in the data table,
to the key in the color map object...
var colors = [];
var colorMap = {
'Men': '#5cb85c',
'Girl': '#000000'
}
for (var i = 0; i < data.getNumberOfRows(); i++) {
colors.push(colorMap[data.getValue(i, 0)]);
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['status', 'number'],
['Men', 5],
['Girl', 7]
]);
var colors = [];
var colorMap = {
'Men': '#5cb85c',
'Girl': '#000000'
}
for (var i = 0; i < data.getNumberOfRows(); i++) {
colors.push(colorMap[data.getValue(i, 0)]);
}
var options = {
title: 'Sex',
is3D: true,
colors: colors
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript"> </script>
<!--Div that will hold the pie chart-->
<div id="piechart"></div>

Related

geochart regions clickable urls

We want to embed a really basic interactive map on our website, where clicking a region will take you to a specific page on our site. We would like to use the regions in google geochart
This is the map we are working with
https://jsfiddle.net/tyvnfxf4/
google.charts.load('current', {'packages':['geochart']});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['England', 400],
['Wales', 300],
['Scotland', 400],
['Ireland', 600],
]);
var options = {
region: 'GB',
resolution: 'provinces',
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
And we would want:
Wales to link to www.example.com/wales
Ireland to link to www.example.com/ireland
etc
Can any help?
Many thanks
there are a number of ways to handle, but the key is using the 'select' event
keep in mind, the 'select' event is fired both when something is selected and de-selected,
so make sure length > 0
recommend using a column in the DataTable to store the URLs
use a DataView to hide the column from the chart
then get the URL based on the chart selection
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity', 'Domain'],
['England', 400, 'www.example.com/England'],
['Wales', 300, 'www.example.com/Wales'],
['Scotland', 400, 'www.example.com/Scotland'],
['Ireland', 600, 'www.example.com/Ireland'],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
region: 'GB',
resolution: 'provinces'
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
if (selection.length > 0) {
console.log(data.getValue(selection[0].row, 2));
//window.open('http://' + data.getValue(selection[0].row, 2), '_blank');
}
});
chart.draw(view, options);
},
packages:['geochart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://www.google.com/jsapi"></script>
<div id="regions_div" style="width: 600px; height: 500px;"></div>

how to draw a google pie (or donut) chart with data from database

I want to draw a pie or donut chart on my MVC project. I can draw it without database. But I want to draw it with data from database. How can I do that?
Here is my sample code for donut chart without database:
<html>
<head>
<title>Chart</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="donutchart" style="width: 900px; height: 500px;"></div>
</body>
</html>
You basically need to generate the data similar to your javascript array in your action method and pass that to your view. I have hard coded it here. But you may replace it with data from your db.
public ActionResult Index()
{
var data = new List<List<object>>()
{
new List<object>
{
"Task","Hours per day"
},
new List<object>
{
"Work",45
}
,
new List<object>
{
"Eat",25
},
new List<object>
{
"Commute to work",30
}
};
return View(data);
}
Now your view will be strongly typed to List<List<object>>
#model List<List<object>>
Now in the same view's script section, serialize your model to a js variable(array) and use that as the input to the arrayToDataTable method.
var dataArr = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
var data = google.visualization.arrayToDataTable(dataArr);

Region Geochart region America

I am learning to use the google Geochart tools I want to recreate a map like this one:
https://docs.google.com/spreadsheets/d/171U4NeI_49iacbhzlX0A8nT6aB9N4guc6VWsELmP6wI/pubchart?oid=1478243202&format=interactive
My code is this:
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['States', 'Number of killings'],
['California', 292],
['Texas', 143],
['Washington', 120]
]);
var options = {
region: 'US'
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
I am able o see the map, but I dont see the state divisions nor the colour I am using http://jsfiddle.net, I am sure it is a very basic error but I cant find it.
Add {resolution: provinces}:
working code snippet:
google.setOnLoadCallback(drawRegionsMap);
google.load('visualization', '1', {
packages: ['map']
});
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['States', 'Number of killings'],
['California', 292],
['Texas', 143],
['Washington', 120]
]);
var options = {
region: 'US',
resolution: 'provinces'
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
<script src="https://www.google.com/jsapi"></script>
<div>
<div id="regions_div" style="width: 500px; height: 400px;"></div>
</div>

Google Charts Does not render for a scatter plot with multiple colors

I am plotting up data in Google Charts and continue to have trouble rendering my HTML. I could sure use a second pair of eyes to check if there is anything obviously wrong with the code below. The data has three columns, each of which is meant to be plotted a different color.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load("visualization", "1", {packages:["corechart"]});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = google.visualization.arrayToDataTable()({
[['x','Virg','Set','Versi'],
[1.0,null,null,1.0],
[2.0,null,2.0,null],
[3.0,3.0,null,null]]
});
// Set chart options
var options = {
title: "Edgar Anderson's Iris Data Set",
hAxis: {title: 'Petal Length', minValue: 0, maxValue: 7},
vAxis: {title: 'Petal Width', minValue: 0, maxValue: 2.5},
legend: ''
//series:{
// 0: { pointShape: 'circle' },
// 1: {pointShape: 'triangle'},
// 2: { pointShape: 'square'}
// }
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Call to arrayToDataTable() is wrong. Instead of
var data = google.visualization.arrayToDataTable()({
[['x','Virg','Set','Versi'],
[1.0,null,null,1.0],
[2.0,null,2.0,null],
[3.0,3.0,null,null]]
});
you have to use
var data = google.visualization.arrayToDataTable([
['x','Virg','Set','Versi'],
[1.0,null,null,1.0],
[2.0,null,2.0,null],
[3.0,3.0,null,null]
]);
Instead of an object of array you have to provide an array of arrays. And unnecessary () deleted.
**Update: ** example at jsbin.

How can I get Selection in dashboard with ChartWrapper

I´m trying to get an event in a google dashboard ChartWrapper.
I need that when I select a row i can throw an event and get the selected value.
Can anyone help me or say me how can I get it?
Here´s my code:
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['controls']});
</script>
<script type="text/javascript">
var data;
var table;
var dash_container;
var myDashboard;
var stringFilter;
var myTable;
function draw() {
// To see the data that this visualization uses, browse to
// http://spreadsheets.google.com/ccc?key=pCQbetd-CptGXxxQIG7VFIQ
data = new google.visualization.Query(
'http://spreadsheets.google.com/tq?key=0Ai3BbtO5JfaodGluSWw0UVFvZ3BDak1nYzVac0RPWGc&pub=1');
// Send the query with a callback function.
data.send(handleQueryResponse);
}
//fin de draw
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
table = response.getDataTable();
// Create a dashboard.
dash_container = document.getElementById('dashboard'),
myDashboard = new google.visualization.Dashboard(dash_container);
// Define a StringFilter control for the 'Name' column
stringFilter = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'filter',
'options': {'filterColumnLabel': 'nombre'}
});
// Table visualization
myTable = new google.visualization.ChartWrapper({
'chartType' : 'Table',
'containerId' : 'table',
'view': {'columns': [0]} ,
'dataTable': table
});
// Register a listener to be notified once the dashboard is ready.
google.visualization.events.addListener(myDashboard, 'ready', dashboardReady);
myDashboard.bind(stringFilter, myTable);
myDashboard.draw(table);
}
**Here´s where I have the problems, because I can get the selection row
function dashboardReady() {
google.visualization.events.addListener(myTable, 'select', function(event) {
var selection = myTable.getChart().getSelection();
// iterate over all selected rows
for (var i = 0; i < selection.length; i++) {
// do something with selection[i].row
var item = selection[i];
}
alert('Fila seleccionada es: '+item.row +' y la Columna: '+item.column);
});
}
google.setOnLoadCallback(draw);
To do that, you need to do two things after the chart is drawn:
Add a 'ready' event listener to your chart wrapper;
Add a 'select' event listener to the table when the chart wrapper is ready.
So, add the following two lines after myDashboard.draw(table); in your code
google.visualization.events.addListener(myTable , 'ready', function(){
google.visualization.events.addListener(myTable ,'select', tableSelectHandler);
});
function tableSelectHandler(){
var selection = myTable.getChart().getSelection();
alert(data.getValue(selection[0].row,0));
}
There will be about 3 seconds delay for the ready function to be triggered, due to a bug I think, see here for more details about the bug report of this issue: https://code.google.com/p/google-visualization-api-issues/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Stars%20Modified%20Type%20Status%20Priority%20Milestone%20Owner%20Summary&groupby=&sort=&id=1470
With Wrapper you have to add one more function to get selected item i.e. getChart()
Like:
var selectedItem = wrapper.getChart().getSelection()
Remember, Without Wrapper you was getting it by:
var selectedItem = chart.getSelection()
The code working ...
google.setOnLoadCallback(draw);
function draw() {
var data = [
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
];
var table = google.visualization.arrayToDataTable(data);
// Create a dashboard.
var dash_container = document.getElementById('dashboard');
var myDashboard = new google.visualization.Dashboard(dash_container);
// Define a StringFilter control.
var stringFilter = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'filter',
'options': {'filterColumnLabel': 'Year'}
});
// Table visualization
var myTable = new google.visualization.ChartWrapper({
'chartType' : 'Table',
'containerId' : 'table',
'view': {'columns': [0, 1]} ,
'dataTable': table,
});
myDashboard.bind(stringFilter, myTable);
myDashboard.draw(table);
google.visualization.events.addListener(myTable , 'ready', function(){
google.visualization.events.addListener(myTable ,'select', tableSelectHandler);
});
function tableSelectHandler(e){
var selection = myTable.getChart().getSelection();
var t=table.getValue(selection[0].row, 0);
document.getElementById('label1').innerHTML = t;
}
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('visualization', '1.1', {packages: ['controls']});</script>
<script type="text/javascript">
</script>
</head>
<body>
<div id="filter"></div>
<br>
<div id="table"></div>
<br>
<div id="label1"></div>
</body>
</html>