I have created a Google Pie Chart using the following code:
var data = google.visualization.arrayToDataTable(array);
var options = {
title: 'Meta Share',
is3D: true,
sliceVisibilityThreshold: .04,
slices: { 6 : {offset: 0.2},
},
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I want to select a slice of the pie chart dynamically depending on what my user is doing.
I now have the following code:
var slice = 8;
I would now like to use this variable in the above code, however; replacing the '6' with the variable 'slice' does not work.
Any suggestions? :)
You can't use variables as keys in object literals, you'd have to first create the object, then use brackets to use the variable as a key
var slice = 8;
var slices = {};
slices[slice] = {offset: 0.2};
var data = google.visualization.arrayToDataTable(array);
var options = {
title : 'Meta Share',
is3D : true,
sliceVisibilityThreshold : .04,
slices : slices
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Related
I have a page in an app that displays all sorts of ticket metrics from several different ticketing systems we use. I use the same function to build each of the charts and display them:
function drawChart(chartData, chartStyle, chartTitle, chartSpanID) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Hour');
data.addColumn('number', 'Tickets');
data.addRows(chartData);
if(chartStyle == "column"){
var chart = new google.visualization.ColumnChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,chartArea: {left: 30, top:20, bottom:30, right:10},animation:{startup: true, duration:2000}}
};
if(chartStyle == "pie"){
var chart = new google.visualization.PieChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,
chartArea:{left: 0, top:20, bottom:10, right: 0},
is3D: true,
sliceVisibilityThreshold: .01,
animation:{startup: true,easing: 'in', duration:1000},
pieResidueSliceLabel: "Other( < 1%)"};
};
chart.draw(data, options);
}
This works for 13 of the 14 charts displayed on the page. 8 Columns and 5 out of 6 pie charts all display perfectly. One of the pie charts will ONLY display if I draw the chart a second time.
function drawChart(chartData, chartStyle, chartTitle, chartSpanID) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Hour');
data.addColumn('number', 'Tickets');
data.addRows(chartData);
if(chartStyle == "column"){
var chart = new google.visualization.ColumnChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,chartArea: {left: 30, top:20, bottom:30, right:10},animation:{startup: true, duration:2000}}
};
if(chartStyle == "pie"){
var chart = new google.visualization.PieChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,
chartArea:{left: 0, top:20, bottom:10, right: 0},
is3D: true,
sliceVisibilityThreshold: .01,
animation:{startup: true,easing: 'in', duration:1000},
pieResidueSliceLabel: "Other( < 1%)"};
};
chart.draw(data, options);
chart.draw(data, options);
}
The data is delivered correctly, all calls are made through google.charts.setOnLoadCallback, it all works just fine once called again... so why is it only working on the second call? Why just the one chart that doesn't display as expected? What have I missed?
I made a chart in chartJS and I would like to update it using new data based on what the user chooses from a drop down list, using the same canvas. The problem is when i do the update function, the chart updates with the new data but it keeps coming back to the original chart after a while. How can i solve this? Here's the code, thank you for any help:
/* Original Chart */
var ctx3 = document.getElementById("canvas3").getContext("2d");
var canvas3 = new Chart(ctx3, {
type: 'line',
data: {
labels: stationRentalsLabels,
datasets: [{
label: 'Wypożyczenia',
fillColor: "rgba(220,280,220,0.5)",
strokeColor: "rgba(220,220,220,1)",
backgroundColor: "rgba(153,255,51,0.4)",
data: stationRentalsData
}]
}
});
/* event listener on drop-down list, when triggered, update chart */
select.addEventListener('change', function() {
updateChart()
});
/* Update Chart */
function updateChart() {
var stationRentalsHoursTemp = [];
var stationRentalName = [];
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++) {
if (determineHour == stationRentalsHours[i]) {
stationRentalsHoursTemp.push(stationRentalsData[i])
stationRentalName.push(stationRentalsLabels[i]);
}
}
/* Updated Chart */
var ctx3 = document.getElementById("canvas3").getContext("2d");
var canvas3 = new Chart(ctx3, {
type: 'line',
data: {
labels: stationRentalName,
datasets: [{
label: 'Wypożyczenia',
fillColor: "rgba(220,280,220,0.5)",
strokeColor: "rgba(220,220,220,1)",
backgroundColor: "rgba(153,255,51,0.4)",
data: stationRentalsHoursTemp
}]
}
});
}
You are creating new chart on update function in the same div as before but in order to do that you need to destroy the previous instance of the chart by calling the destroy function before calling the updateChart function.
canvas3.destroy();
Another approach to solving your problem is by replacing the data not the chart itself when the updateChart function is called by calling the update function(Not initializing a new chart)
function updateChart() {
var stationRentalsHoursTemp = [];
var stationRentalName = [];
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++) {
if (determineHour == stationRentalsHours[i]) {
stationRentalsHoursTemp.push(stationRentalsData[i])
stationRentalName.push(stationRentalsLabels[i]);
}
}
// just update the label and dataset not the entire chart
canvas3.data.labels = stationRentalName;
canvas3.data.datasets[0].data = stationRentalsHoursTemp;
canvas3.update();
}
I have a json with the name of each server and 3 values: memory, load and cpu.
[
{
"server": "Server1",
"Load": "0.04",
"Mem": "64.46",
"Idle": "97.00"
},
{
"server": "Server2",
"Load": "0.01",
"Mem": "64.79",
"Idle": "97.49"
}
]
I'm having some issues trying to create Google Chart dynamically. Looks like Javascript can't create variables using the loop variable 'i'. See my code below:
var obj = JSON.parse(jsonData);
for (i in obj)
{
var data_table[i] = new google.visualization.DataTable();
data_table[i].addColumn('string', 'Label');
data_table[i].addColumn('number', 'Value');
var server = obj[i].server;
var Load = parseFloat(obj[i].Load);
var Mem = parseFloat(obj[i].Mem);
var Idle = parseFloat(obj[i].Idle);
data_table[i].addRow([server, Load]);
data_table[i].addRow([server, Mem]);
data_table[i].addRow([server, Idle]);
var options = {width: 1500, height: 1000, redFrom: 90, redTo: 100, yellowFrom:75, yellowTo: 90, minorTicks: 5};
var chart[i] = new google.visualization.Gauge(document.getElementById('chart_div'+ i +));
chart[i].draw(data_table+i+, options); ' );
$('body').append('<div id="div'+ i +'" />')
}
I want to create the Chart dynamically to control these chart's later in the javascript/html and also and most important because my json is a little big so I want to avoid to have to create each chart one by one, or have to separate the json for each server.
Any help will be really appreciated. ;-)
Try it like this...
// load json
var obj = JSON.parse(jsonData);
// define arrays to store data and charts
var data_tables = [];
var google_charts = [];
// this is the div that will store all of the charts
var chart_area;
chart_area = document.getElementById('chart_div');
// set the chart options
var chart_options;
chart_options = {
width: 1500,
height: 1000,
redFrom: 90,
redTo: 100,
yellowFrom: 75,
yellowTo: 90,
minorTicks: 5
};
// process json array -- fyi: use 'in' keyword for object keys
for (var i = 0; i < obj.length; i++) {
var chart_container; // chart container for this json instance
var data_table; // data table for this json instance
var google_chart; // google chart for this json instance
// load data table
data_table = new google.visualization.DataTable();
data_table.addColumn('string', 'Label');
data_table.addColumn('number', 'Value');
data_table.addRow([obj[i].server, parseFloat(obj[i].Load)]);
data_table.addRow([obj[i].server, parseFloat(obj[i].Mem)]);
data_table.addRow([obj[i].server, parseFloat(obj[i].Idle)]);
// save it to the array
data_tables.push(data_table);
// create the container for this chart
chart_container = document.createElement('DIV');
chart_area.appendChild(chart_container);
// create -- save -- draw the chart
google_chart = new google.visualization.Gauge(chart_container);
google_charts.push(google_chart);
google_chart.draw(data_table, chart_options);
}
// access the charts / data later using arrays --> data_tables and google_charts
In my example, the data is generated randomly. After click on button, zoom type should be changed.
$(function() {
var chartOptions={
chart:{
zoomType : 'x',
events : {
load : function() {
var series = this.series[0];
var chart = this;
setInterval(function() {
var x = (new Date()).getTime(),
y = Math.round(Math.random() * 100);
series.addPoint([x, y]);
chart.redraw();
}, 1000);
}
}
},
series : [{
name : 'AAPL',
data : [null]
}]
};
$('#container').highcharts('StockChart', chartOptions);
$('#button').click(function() {
var chart1 = $('#container').highcharts();
//alert(chart1.series[0].yData);
chartOptions.chart.zoomType = 'y';
$('#container').highcharts(chartOptions);
});
});
After click button, the old chart disappears but the new one is not generated.
Firebug shows TypeError: e is undefined and in the line series.addPoint([x, y]); shows series is undefined.
chartOptions is global so in the click handler, one property (zoomType) is changed and the rest should be the same.
alert(chart1.series[0].yData); shows the propery y data. So I tried:
$('#button').click(function() {
var chart1 = $('#container').highcharts();
//alert(chart1.series[0].yData);
chartOptions.chart.zoomType = 'y';
var chart2 = $('#container').highcharts(chartOptions);
chart2.series[0].setData(chart1.series[0].data);
chart2.redraw();
});
Then firebug shows chart2.series is undefined.
You cannot update zoom type in highcharts, without destroy() chart and create new instance. In other words, you should use
chart1.destroy()
var chart2 = $('#container').highcharts(chartOptions);
In case when you would like set range on any axis (zoom chart) you can use setExtremes() function http://api.highcharts.com/highstock#Axis.setExtremes()
When chartOptions or chart2.series is undefinded you need to use $.extend({},chartoptions)
$('#container').highcharts($.extend({},chartoptions);
I seem to be unable to get this Google Chart Scatter Plot to display the score.partner as a label. I can only get them to show as tooltips.
What am I doing wrong?
drawChart: function() {
var self = this;
var gdpMin = parseFloat(self.scores[0].gdpScore);
var gdpMax = gdpMin;
var teaMin = parseFloat(self.scores[0].teaScore);
var teaMax = teaMin;
var data = new google.visualization.DataTable();
data.addColumn('number', 'GDP Score');
data.addColumn('number', 'TEA Score');
data.addColumn({type:'string', role:'label'});
$.each(self.scores, function(i, score) {
gdpScore = parseFloat(score.gdpScore);
teaScore = parseFloat(score.teaScore);
data.addRows([[gdpScore, teaScore, score.partner]]);
if (gdpScore < gdpMin) gdpMin = gdpScore;
if (gdpScore > gdpMax) gdpMax = gdpScore;
if (teaScore < teaMin) teaMin = teaScore;
if (teaScore > teaMax) teaMax = teaScore;
});
var options = {
title: 'GDP and TEA Scores',
hAxis: {title: 'GDP', minValue: gdpMin, maxValue: gdpMax},
vAxis: {title: 'TEA', minValue: teaMin, maxValue: teaMax},
legend: 'none',
colors: ['#3B7CBF']
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
From user asgallant in Google Visualization API Group:
You want to label individual points on a ScatterChart? That isn't
supported. Depending on the structure of your data, you may be able
to use a LineChart in a manner similar to a ScatterChart. See an
example here: jsfiddle.net/asgallant/YFMga/
There you have it. Labels are not supported for scatter plots using the Google Visualization API.
jqPlot may be an acceptable alternative.