Google Line Chart - How to display data to linegraph - javascript

See the following data.DataTable
How do I input this data into Google Line Charts with filter for each Column AND filter for the Dates.
I would like my graph to have x-axis of dates and y-axis with the percentage. Also each row of data is its own line in the line graph. Is this possible?
Below is a snippet part of my code:
var data = google.visualization.arrayToDataTable(response,false);
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard-div'));
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table-div',
'options': {'backgroundColor': 'lightgrey'}
});
var numCol = [3];
for (var i = 10; i < data.getNumberOfColumns(); i++) {
numCol.push(i);
}
var line = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'linechart-div',
'view': {'columns': numCol},
'options': {'backgroundColor': 'lightgrey', 'title': 'InterCarrier Trunk Capacity Graph', 'explorer': {
'actions': ['dragToZoom', 'rightClickToReset'],
'axis': 'horizontal',
}}
});
var Slider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'slider-div1',
'options': {
'filterColumnLabel': '3/1/2020'
}
});
var Slider2 = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'slider-div2',
'options': {
'filterColumnLabel': '3/2/2020'
}
});
var Slider3 = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'slider-div3',
'options': {
'filterColumnLabel': '3/3/2020'
}
});
var Slider4 = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'slider-div4',
'options': {
'filterColumnLabel': '3/4/2020'
}
});
Chart Here

Related

Google Visualization PHP and Javascript

I am creating a chart using a while loop to get the variables from a mysql query.
I am attempting to add html to the first column and it is causing the following issue: [object Object] does not fit either the Control or Visualization specification.
So, the table displays correctly but my category filters are now throwing this error. Can someone take a look at my code and see what i am missing? Thanks!
Here is my code:
echo "<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<body>
<br><br>
<div id='dashboard'>
<div style='float:left;' id='control1'></div>
<div style='float:left;' id='control2'></div>
<div style='float:left;' id='control4'></div>
<br><br>
<div style='float:left;' id='control3'></div>
<div style='float:left;' id='control5'></div>
<br><br>
<div id='table'></div>
</div>
</body>";
echo "<script>
google.load('visualization', '1.0', {packages:['corechart', 'table', 'controls']});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = new google.visualization.DataTable();
data.addColumn('string', 'Save');
data.addColumn('string', 'School');
data.addColumn('string', 'State');
data.addColumn('string', 'Scholarship Type');
data.addColumn('string', 'Scholarship Amount');
data.addColumn('string', 'For International');";
while ($schools = mysql_fetch_row($schoolsearch)) {
$schoolnames = str_replace(array('.', ',', "'"), '' , $schools[2]);
echo "data.addRows([
['<input type=\"checkbox\">', '$schoolnames', '$schools[1]', '$schools[6]', '$schools[5]', '$schools[7]'],
]);";
}
echo "var name_filter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control1',
'options': {
'filterColumnLabel': 'School',
}
});
var state_filter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'State',
}
});
var scholarshiptype_filter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control3',
'options': {
'filterColumnLabel': 'Scholarship Type',
}
});
var scholarshipamount_filter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control4',
'options': {
'filterColumnLabel': 'Scholarship Amount',
}
});
var international_filter = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control5',
'options': {
'filterColumnLabel': 'For International',
}
});
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table',
});
var table = new google.visualization.Table(document.getElementById('table'));
table.draw(data, {
allowHtml:true,
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard'));
dashboard.bind([name_filter, state_filter, scholarshiptype_filter, scholarshipamount_filter, international_filter], [table]);
dashboard.draw(data);
}
</script>
I was able to fix this by placing the allowHtml in the options like this:
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table',
options: {
allowHtml: true
},
});
another option, which may work better, depending on if you want the filter to work on the html or the value it represents...
each cell in a DataTable has a value (v:) and a formatted value (f:)
you can use the formatted value for the html
where you have...
echo "data.addRows([
['<input type=\"checkbox\">', '$schoolnames', '$schools[1]', '$schools[6]', '$schools[5]', '$schools[7]'],
]);";
try...
echo "data.addRows([
[{v: '', f: '<input type=\"checkbox\">'}, '$schoolnames', '$schools[1]', '$schools[6]', '$schools[5]', '$schools[7]'],
]);";

Resizing google visualization with ChartEditor

is it possible to set the width and height of a chart when using the google visualization ChartEditor?
I require the chart to be 100% the width of the page and then set the height in pixels, currently when I set the width and height in the options they are being ignored.
the code that I have worked on so far is below:
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart", "controls", "charteditor"] });
google.setOnLoadCallback(loadEditor);
var chartEditor = null;
window.onresize = function() {
loadEditor();
};
function loadEditor() {
var data = google.visualization.arrayToDataTable([#Html.Raw(#ViewBag.ChartData)]);
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
var rangeSlider = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'VAR1',
'ui': {
'label': 'Years'
}
}
});
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
dataTable: data
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
chartEditor.openDialog(wrapper, {});
dashboard.bind(rangeSlider, wrapper);
dashboard.draw(data);
}
function redrawChart() {
chartEditor.getChartWrapper().draw(document.getElementById('chart_div'));
}
</script>
the chart also incorporates a CategoryFilter linked with a dashboard is required to work with the chart displayed.
Currently when the chart is rendered it is fairly small.
Something like this should work, I switched out the data and modified the slider to get the snippet to work.
google.load("visualization", "1", { packages: ["corechart", "controls", "charteditor"] });
google.setOnLoadCallback(loadEditor);
window.addEventListener('resize', redrawChart, false);
var chartEditor;
var data;
var dashboard;
var rangeSlider;
var wrapper;
function loadEditor() {
data = google.visualization.arrayToDataTable([
['Element', 'Density'],
['Copper', 8.94],
['Silver', 10.49],
['Gold', 19.30],
['Platinum', 21.45]
]);
dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
rangeSlider = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'Density',
'ui': {
'label': 'Density'
}
}
});
wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
dataTable: data
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', drawChart);
chartEditor.openDialog(wrapper, {});
}
function drawChart() {
wrapper = chartEditor.getChartWrapper();
redrawChart();
}
function redrawChart() {
var height;
var width;
height = '200px';
width = Math.min(document.documentElement.clientWidth, window.innerWidth || 0) + 'px';
wrapper.setOption('height', height);
wrapper.setOption('width', width);
dashboard.bind(rangeSlider, wrapper);
dashboard.draw(data);
}
<script src="https://www.google.com/jsapi"></script>
<div id="dashboard_div">
<div id="filter_div"></div>
<div id="chart_div"></div>
</div>

Charts API error -- [one or more participants failed to draw()]

I am currently experiencing --> [one or more participants failed to draw()] error on the client side. I am able to get data to output in the drawVisualisation call, hence the issue is within the javascript code. I followed example but I cannot seem to figure out where I may be going wrong to trigger the error.
function drawVisualization(dataValues, chartTitle, columnNames, categoryCaption) {
if (dataValues.length < 1)
return;
var data = new google.visualization.DataTable();
data.addColumn('string', columnNames.split(',')[0]);
data.addColumn('string', columnNames.split(',')[1]);
data.addColumn('number', columnNames.split(',')[2]);
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].Type, dataValues[i].PType, dataValues[i].COUNT]);
}
var line = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart1',
'options': {
'width': '1200',
'height': '500',
'legend': 'none'
},
'view': { 'columns': [2, 0] }
});
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'chart2',
'options': { 'height': '25em', 'width': '80em' }
});
var categoryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'Contorl1',
'options': {
'filterColumnLabel': columnNames.split(',')[1],
'filterColumnIndex': '1',
'ui': {
'label': 'Price'
}
}
});
new google.visualization.Dashboard(document.getElementById('PieChartExample')).bind([categoryPicker], [line, table]).draw(data);
}
</script>
<div id="PieChartExample">
<table>
<tr style='vertical-align: top'>
<td >
<div style="float: left;" id="chart1"></div>
</td>
</tr>
<tr>
<td >
<div style="float: left;" id="chart2"></div>
</td>
</tr>
<tr>
<td style='width: 600px'>
<div style="float: left;" id="control2"></div>
</td>
</tr>
</table>
</div>
Server side code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ClientScript.RegisterStartupScript(this.GetType(), "TestInitPageScript",
string.Format("<script type=\"text/javascript\">google.load('visualization','1.0',{{'packages':['corechart','controls']}});google.setOnLoadCallback(function(){{drawVisualization({0},'{1}','{2}');}});</script>",
jss.Serialize(GetData()),
"Name Example",
"Type,"));
}
}
[WebMethod]
public static List<Data3> GetData()
{
SqlConnection conn = new SqlConnection("##############");
DataSet ds = new DataSet();
DataTable dt = new DataTable();
conn.Open();
string cmdstr = "SELECT [Type], Cover, COUNT(Cover) AS 'Total' FROM [dbo].[database_qy] WHERE [Type] in ('bs','as') GROUP BY Cover, [Type] order by Cover";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
dt = ds.Tables[0];
List<Data3> dataList = new List<Data3>();
string cov = "";
string typ = "";
int val = 0;
foreach (DataRow dr in dt.Rows)
{
try
{
cov = dr[0].ToString();
typ = dr[1].ToString();
val = Convert.ToInt32(dr[2]);
}
catch
{
}
dataList.Add(new Data3(cov, typ, val));
}
return dataList;
}
I am also getting returned to drawVisualisation call, as shown below;
<script type="text/javascript">google.load('visualization','1.0',{'packages': ['corechart','controls']});google.setOnLoadCallback(function(){drawVisualization([{"Type":"bs","PType":"cv","COUNT":2576},{"Type":"cd","PType":"cv","COUNT":2056},{"Type":"cl","PType":"cv","COUNT":9901},{"Type":"cm","PType":"cv","COUNT":10079},{"Type":"rm","PType":"cv","COUNT":12242},{"Type":"bs","PType":"tk","COUNT":3678},{"Type":"cd","PType":"tk","COUNT":7567},{"Type":"cl","PType":"tk","COUNT":42976},{"Type":"cm","PType":"tk","COUNT":21245},{"Type":"rm","PType":"tk","COUNT":44379},{"Type":"bs","PType":"TRD","COUNT":7},{"Type":"cd","PType":"TRD","COUNT":50},{"Type":"cl","PType":"TRD","COUNT":86},{"Type":"cm","PType":"TRD","COUNT":202},{"Type":"rm","PType":"TRD","COUNT":116}],'Name Example','Type,');});</script></form>
Please advice. Thanks
The problem is in the line ChartWrapper's view. The columns you specified ([2, 0]) do not work, as column 0 is a "string" type and cannot be a data series in the chart. Change it to [0, 2] and the dashboard will draw.
var line = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart1',
'options': {
'width': '1200',
'height': '500',
'legend': 'none'
},
'view': { 'columns': [0, 2] }
});
See working example: http://jsfiddle.net/asgallant/8D64L/

Google visualisation error wrong type

Before today all work fine with this code:
var slider;
var ajdi = '';
function drawVisualization() {
var cssClassNames = {
'headerRow': 'zaglavlje',
'tableRow': 'red',
'oddTableRow': 'red1',
'selectedTableRow': 'orange-background large-font',
'hoverTableRow': 'prekoreda',
'headerCell': 'gold-border',
'tableCell': 'cell',
'rowNumberCell': 'underline-blue-font'
};
var json = $.ajax({
url: 'getzadaci.php', // make this url point to the data file
dataType: 'json',
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(json);
//dodajemo kolonu sa kontrolama
//dodajemo kolonu sa kontrolama
data.addColumn('string', '');
for (var y = 0, maxrows = data.getNumberOfRows(); y < maxrows; y++) {
if (data.getValue(y, 11) != 'a') {
data.setValue(y, 11, '<div style="text-align:right;"><a data-toggle="modal" data-target="#update" href="#" class="btn btn-info openRes"><i class="fa fa-edit"></i> Details</a> <a id="hm" data-toggle="modal" data-target="#troskovnik" href="#" class="btn btn-danger"><i class="fa fa-flask"></i> Troskovnik</a> <i data-toggle="modal" data-target="#delete" href="#" class="fa fa-trash-o"></i></div>');
}
}
data.addColumn('string', '');
for (var y = 0, maxrows = data.getNumberOfRows(); y < maxrows; y++) {
if (data.getValue(y, 3) === 'U toku') {
data.setValue(y, 12, '<span class="bg-warning" style="display: inline-block;">U toku</span>');
}
else if (data.getValue(y, 3) === 'U planu') {
data.setValue(y, 12, '<span class="bg-danger" style="display: inline-block;">U planu</span></span>');
}
else {
data.setValue(y, 12, '<span class="bg-success" style="display: inline-block;">Zavrseno</span>');
}
}
// Define a category picker control for the Gender column
var categoryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control1',
'options': {
'filterColumnLabel': 'Status',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': true,
'caption': 'Status'
}
}
});
var categoryPicker1 = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnIndex': 8,
'ui': {
'labelStacking': 'horizontal',
'allowTyping': false,
'allowMultiple': true,
'caption': 'Parcela'
}
}
});
var categoryPicker2 = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control4',
'options': {
'filterColumnIndex': 2,
'ui': {
'labelStacking': 'horizontal',
'allowTyping': false,
'allowMultiple': true,
'caption': 'Vrsta zadatka'
}
}
});
var stringFilter1 = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'control3',
'options': {
'matchType': 'any',
'filterColumnIndex': 1,
'ui': {'labelStacking': 'vertical'}
}
});
var slider = new google.visualization.ControlWrapper({
'controlType': 'DateRangeFilter',
'containerId': 'control5',
'options': {
'filterColumnLabel': 'Pocetak',
'ui': {'labelStacking': 'vertical'}
}
});
// Define a Pie chart
// Define a table
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'chart2',
'cssClassNames': 'cssClassNames',
'view': { 'columns': [1,2,12,5,6,8,11] },
'options': {
cssClassNames: cssClassNames,
allowHtml: true
}
});
var timeline = new google.visualization.ChartWrapper({
chartType: 'Timeline',
containerId: 'chart5',
options: {
height: '350',
timeline: { colorByRowLabel: true },
//timeline.barLabelStyle: {color: '#000', fontName: 'Arial', fontSize: '13px'},
backgroundColor: '#fff',
colors: ['#55c2a2', '#89d168', '#d3eb87','#8ec63e', '#FFF0BA','#FF542E', '#CFD6DE', '#ADC1D6', '#7297BA']
//timeline: { rowLabelStyle: {fontName: 'Helvetica', fontSize: 24, color: '#603913' },
// barLabelStyle: { fontName: 'Garamond', fontSize: 14 } }
},
view: {
// as an example, use columns "Naziv", "Vrsta", "Pocetak", and "Zavrsetak" for the timeline
columns: [8, 2, 5, 6]
},
});
var formatter_short = new google.visualization.DateFormat({formatType: 'short'});
formatter_short.format(data, 5);
formatter_short.format(data, 6);
new google.visualization.events.addListener(table, 'ready', function () {
google.visualization.events.addListener(table.getChart(), 'select', function () {
var selection = table.getChart().getSelection();
// iterate over all selected rows
for (var i = 0; i < selection.length; i++) {
//$("#edit").removeClass("edit btn btn-success")
//$('#edit').addClass('edit btn btn-success');
ajdi = table.getDataTable().getValue(selection[i].row,0);
openResource();
$("#vrednostid").val(table.getDataTable().getValue(selection[i].row,0));
$("#naziv1").val(table.getDataTable().getValue(selection[i].row,1));
$("#vrsta_rada1").val(table.getDataTable().getValue(selection[i].row,2));
$("#status1").val(table.getDataTable().getValue(selection[i].row,3));
$("#opis1").val(table.getDataTable().getValue(selection[i].row,4));
$("#usluzno1").val(table.getDataTable().getValue(selection[i].row,9));
var p = new Date(table.getDataTable().getValue(selection[i].row,5));
$("#dp31").datepicker("setDate", p);
var z = new Date(table.getDataTable().getValue(selection[i].row,6));
$("#dp41").datepicker("setDate", z);
//$("#parcele1").val(table.getDataTable().getValue(selection[i].row,8));
//$("#parcele1").select2("val", ["3","19"]);
var id = table.getDataTable().getValue(selection[i].row,10);
var naziv = table.getDataTable().getValue(selection[i].row,8);
var idArr = (id.lastIndexOf(',') == (id.length - 1) ? id.substr(0, id.length - 1) : id).split(', ');
var nazivArr = (naziv.lastIndexOf(',') == (naziv.length - 1) ? naziv.substr(0, naziv.length - 1) : naziv).split(', ');
var objHold = [];
for(var j=0,length=idArr.length;j<length;j++)
{
if(idArr[j] && nazivArr[j]) // make sure both arrays have a value
objHold.push({id: idArr[j], naziv: nazivArr[j]});
}
$("#parcele1").select2("data", objHold);
}
});
});
// Create a dashboard
new google.visualization.Dashboard(document.getElementById('dashboard')).
// Establish bindings, declaring the both the slider and the category
// picker will drive both charts.
bind([categoryPicker, categoryPicker1, categoryPicker2, slider, stringFilter1], [table, timeline]).
// Draw the entire dashboard.
draw(data, {'allowHtml':true, 'cssClassNames': 'cssClassNames'});
//table.draw(data, {'allowHtml':true, 'cssClassNames': cssClassNames});
}
function dashboardReady() {
// The dashboard is ready to accept interaction. Configure the buttons to
// programmatically affect the dashboard when clicked.
// Change the slider selected range when clicked.
document.getElementById('rangeButton').onclick = function() {
slider.setState({'lowValue': 2, 'highValue': 5});
slider.draw();
};
// Change the pie chart rendering options when clicked.
document.getElementById('optionsButton').onclick = function() {
piechart.setOption('is3D', true);
piechart.draw();
};
}
google.setOnLoadCallback(drawVisualization);// JavaScript Document
but today I just get this error: You called the draw() method with the wrong type of data rather than a DataTable or DataView×
Why? I'm so nervous ith google viz api...
Is there any change to make it workable? Is there any option to disable google visualisation error for dashboard, becouse when I dont have data Google show me an error
UPDATE:
I had the same problem on chrome v. 35 after the recent charts update.
Cleared my browsing history (shift + ctl + del) and it fixed the problem.
Must have been something to do with a cookie from the previous version of the google charts.

Google chart percentage slider

<script type="text/javascript">
function drawVisualization1(dataValues, chartTitle, columnNames, categoryCaption) {
if (dataValues.length < 1)
return;
var data = new google.visualization.DataTable();
data.addColumn('string', columnNames.split(',')[0]);
data.addColumn('string', columnNames.split(',')[1]);
data.addColumn('string', columnNames.split(',')[2]);
data.addColumn('string', columnNames.split(',')[3]);
data.addColumn('string', columnNames.split(',')[4]);
data.addColumn('string', columnNames.split(',')[5]);
data.addColumn('number', columnNames.split(',')[6]);
data.addColumn('number', columnNames.split(',')[7]);
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].Value1, dataValues[i].Value2, dataValues[i].Value3, dataValues[i].Value4, dataValues[i].Value5, dataValues[i].Value6,( dataValues[i].Value7)/100, (dataValues[i].Value8)/100]);
}
var formatter = new google.visualization.NumberFormat({ pattern: '####%' });
formatter.format(data, 6);
var formatter = new google.visualization.NumberFormat({ pattern: '####%' });
formatter.format(data, 7);
var categoryPicker1 = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'Container',
'options': {
'filterColumnLabel': columnNames.split(',')[2],
'ui': {
'labelStacking': 'horizontal',
'allowTyping': false,
'allowMultiple': false,
'caption': categoryCaption,
'label': columnNames.split(',')[2]
}
}
});
var slider1 = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'Slider',
'options': {
'filterColumnLabel': columnNames.split(',')[6],
'ui': { 'labelStacking': 'horizontal' },
'ui.format': { 'pattern':'####%' }
}
});
var table1 = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'TableContainer1',
'options': {
'width': '895px',
'page': 'enable',
'pageSize': 5
}
});
new google.visualization.Dashboard(document.getElementById('PieChartExample')).bind([categoryPicker1, slider1], [table1]).draw(data);
}
</script>
Script code to generate google chart my problem is i am not able to show the slider for percentage values;i am converting that table values into percentage and i want to show in the slider value.can anyone help me to resolve.
var slider1 = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'Slider',
'options': {
'filterColumnLabel': columnNames.split(',')[6],
'ui': { 'labelStacking': 'horizontal',
'format': { 'pattern':'####%' } }
}
});

Categories

Resources