Google Charts, how can i set a calculated view in a ChartWrapper? - javascript

i use the ChartWrapper from google charts.. my actual implementation looks like this:
var dataTable=new google.visualization.DataTable(DATA);
var options = {
title: 'Name of the Chart',
vAxis: {title: "Cups"},
hAxis: {title: "Month"},
isStacked: false,
pointSize: 3
};
var chartWrapperArgs = {
chartType: "LineChart",
dataTable: dataTable,
view: {"columns":[0,1,2]},
options: options,
containerId: "chart"]
};
var chartWrapper = new google.visualization.ChartWrapper(chartWrapperArgs);
chartWrapper.draw();
the problem is, sometimes i must change the data type from "date" to "string" i do this in my old implementation(there is no ChartWrapper) like this:
var dataView = new google.visualization.DataView(dataTable);
dataView.setColumns([{
type: 'string',
label: dataView.getColumnLabel(0),
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
}
}, 1]);
this works and now i have tried the same with my ChartWrapper implementation but with no success:
i have tried this two approaches:
1.)
var dataTable=new google.visualization.DataTable(DATA);
var chartWrapperArgs = {
chartType: "LineChart",
dataTable: dataTable,
view: {"columns":[
{
type: 'string',
label: dataTable.getColumnLabel(0),
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
}
},
1
]},
options: options,
containerId: "chart"]
};
var chartWrapper = new google.visualization.ChartWrapper(chartWrapperArgs);
and my second:
var dataTable=new google.visualization.DataTable(DATA);
var dataView = new google.visualization.DataView(dataTable);
dataView.setColumns([{
type: 'string',
label: dataView.getColumnLabel(0),
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
}
}, 1]);
var ViewData= dataView.toJSON();
var chartWrapperArgs = {
chartType: "LineChart",
dataTable: dataTable,
view: ViewData,
options: options,
containerId: "chart"]
};
var chartWrapper = new google.visualization.ChartWrapper(chartWrapperArgs);
but this did also not worked..
what do i wrong ?
i know i can set the view directly to the dataTable like "dataTable : view" but i want only do this in the "view:" option or the chartWrapper.setView() option.. or is this not possible ?

Your first method (setting the view parameter) should work, but your code had a syntax error at the end of the containerId: "chart"] line (the ] should not be there):
var chartWrapperArgs = {
chartType: "LineChart",
dataTable: dataTable,
view: {
columns: [{
type: 'string',
label: dataTable.getColumnLabel(0),
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
}
}, 1]
},
options: options,
containerId: "chart"
};
var chartWrapper = new google.visualization.ChartWrapper(chartWrapperArgs);
If that isn't working, can you post a full example demonstrating the problem?

Related

How to show a value in google chart [duplicate]

I need to put labels over my google.chart.Bar (not google.visualization.BarChart) the chart is correctly visualized but only shows values on mouse over the bars,please helpme!.
without mouse over
with mouse over
the data is taked from hidden inputs... here the code :
var data3 = new google.visualization.arrayToDataTable([
['Ambitos', 'Programados', 'Terminados',{ role: 'style' }],
['ex', parseInt(document.getElementById("sumex").value),(parseInt(document.getElementById("sumex").value))-( parseInt(document.getElementById("sumpex").value)),document.getElementById("sumex").value],
['ma', parseInt(document.getElementById("summa").value),(parseInt(document.getElementById("summa").value))-( parseInt(document.getElementById("sumpma").value)),document.getElementById("summa").value],
['mo', parseInt(document.getElementById("summo").value),(parseInt(document.getElementById("summo").value))-( parseInt(document.getElementById("sumpmo").value)),document.getElementById("summo").value],
['re', parseInt(document.getElementById("sumre").value),(parseInt(document.getElementById("sumre").value))-( parseInt(document.getElementById("sumpre").value)),document.getElementById("sumre").value],
['tx', parseInt(document.getElementById("sumtx").value),(parseInt(document.getElementById("sumtx").value))-( parseInt(document.getElementById("sumptx").value)),document.getElementById("sumtx").value]]);
var view3 = new google.visualization.DataView(data3);
view3.setColumns([0,1,2,
{ calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation" },3]);
var options3 = {
legend: { position: "none" },
chart: {
title: 'Resumen General',
subtitle: 'programados v/s terminados'},
series: {},
axes: { y: {
distance: {label: ''}, } },
chartArea : { width:"95%", height:"80%"} };
var chart3 = new google.charts.Bar(document.getElementById('barras'));
chart3.draw(data3, options3);
p.d. sorry for my bad english!
unfortunately, annotations (bar labels) are not supported on Material charts
recommend using Core chart, with the following option instead...
theme: 'material'
an separate annotation column should be added for each series column,
that should have annotations
when using a DataView to add annotation columns,
be sure to draw the chart using the view (view3),
instead of the original data table (data3)
see following working snippet...
google.charts.load('current', {
callback: function () {
var data3 = new google.visualization.arrayToDataTable([
['Ambitos', 'Programados', 'Terminados',{ role: 'style' }],
['ex', 8,(8)-(6),''],
['ma', 6,(6)-(4),''],
['mo', 4,(4)-(2),''],
['re', 2,(2)-(1),''],
['tx', 1,(1)-(0),'']]);
var view3 = new google.visualization.DataView(data3);
view3.setColumns([0,
1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2,
{
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
},
3
]);
var options3 = {
legend: { position: "none" },
chart: {
title: 'Resumen General',
subtitle: 'programados v/s terminados'
},
series: {},
axes: {
y: {
distance: {label: ''},
}
},
chartArea : {
width:"95%",
height:"80%"
},
theme: 'material'
};
var chart3 = new google.visualization.ColumnChart(document.getElementById('barras'));
chart3.draw(view3, options3);
},
packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barras"></div>
note: list of options unavailable to Material --> Tracking Issue for Material Chart Feature Parity

Add new column in google DataView dynamically

I'm using google chart datatable getting data from a Json, but I want to add a new column result of divide column 2 by 15000.
Using google.visualization.DataTable()
I'm getting something like this
Colum 1 | Column 2
First row 15.000.000€
Second row 20.000.000€
I want Column 3 like this
Colum 1 | Column 2 | Column 3
First row 15.000.000€ 1.000,00€
Second row 20.000.000€ 1.333,33€
you can use a DataView to add the new column, using a calculated column.
create a data view from the data table
var view = new google.visualization.DataView(data);
then use the setColumns method to change the view columns.
we use the column index of the first two columns,
then use a calculation for the third.
view.setColumns([0, 1, {
calc: function (dt, row) {
return dt.getValue(row, 1) / 15000;
},
label: 'Column 3',
type: 'number'
}]);
see following working snippet...
google.charts.load('current', {
packages: ['table']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Column 1', 'Column 2'],
['First Row', 15000000],
['Second Row', 20000000]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
return dt.getValue(row, 1) / 15000;
},
label: 'Column 3',
type: 'number'
}]);
var table = new google.visualization.Table(document.getElementById('chart_div'));
table.draw(view);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
to format the number,
use google's number formatter,
and object notation for the value.
var formatNumber = new google.visualization.NumberFormat({
pattern: '#,##0.00',
suffix: '€'
});
to format a data table column, use the format method.
formatNumber.format(data, 1);
to format a single value, use the formatValue method.
var value = dt.getValue(row, 1) / 15000;
return {
v: value,
f: formatNumber.formatValue(value)
};
see following working snippet..
google.charts.load('current', {
packages: ['table']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Column 1', 'Column 2'],
['First Row', 15000000],
['Second Row', 20000000]
]);
var formatNumber = new google.visualization.NumberFormat({
pattern: '#,##0.00',
suffix: '€'
});
formatNumber.format(data, 1);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
var value = dt.getValue(row, 1) / 15000;
return {
v: value,
f: formatNumber.formatValue(value)
};
},
label: 'Column 3',
type: 'number'
}]);
var table = new google.visualization.Table(document.getElementById('chart_div'));
table.draw(view);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Moving annotations on Bar Chart with Negative Values Google Chart

I am using google charts within an MVC project.
I am looking to implement a bar chart that has negative values.
I would like the annotations on the negative portion of the chart to be on the same side as the end of the bar (just like the positive, see image below, green box is where I would like annotations to be).
I cant seem to find any documentation on how this can be achieved.
Is it possible to move the annotation to the other side?
there are no standard config options that will move the annotations
but you can move them manually
however, the chart will actually move them back whenever activity occurs,
such as on bar hover
have to use a MutationObserver, or something, to keep them there
use chart methods --> getChartLayoutInterface().getXLocation(value)
to find the location
also, need to adjust the axis window to leave room for the labels
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable({
cols: [
{label: 'x', type: 'string'},
{label: 'y0', type: 'number'},
],
rows: [
{c:[{v: 'Omega'}, {v: -0.95}]},
{c:[{v: 'Large'}, {v: -0.92}]},
{c:[{v: 'Medium'}, {v: 2.76}]},
{c:[{v: 'Tiny'}, {v: 2.03}]}
]
});
var options = {
annotations: {
alwaysOutside: true,
stem: {
color: 'transparent'
},
textStyle: {
color: '#000000'
}
},
hAxis: {
// leave room for annotation
viewWindow: {
min: data.getColumnRange(1).min - 1
}
},
legend: {
position: 'none'
}
};
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
var container = document.getElementById('chart');
var chart = new google.visualization.BarChart(container);
// move annotations
var observer = new MutationObserver(function () {
$.each($('text[text-anchor="start"]'), function (index, label) {
var labelValue = parseFloat($(label).text());
// only negative -- and -- not on tooltip
if ((labelValue < 0) && ($(label).attr('font-weight') !== 'bold')) {
var bounds = label.getBBox();
var chartLayout = chart.getChartLayoutInterface();
$(label).attr('x', chartLayout.getXLocation(labelValue) - bounds.width - 8);
}
});
});
observer.observe(container, {
childList: true,
subtree: true
});
chart.draw(view, options);
},
packages: ['corechart']
});
<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"></div>

How to combine two Highcharts chart types?

Right now I have a simple column chart with following code using Highcharts:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
//some code
},
xAxis: {
categories: []
},
yAxis: {
//some code
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y}'
}
}
},
legend: {
//some code
},
series: []
};
$.getJSON("data/column.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
I now want to add a line chart to the same container, using exactly the same options (despite of the chart type). The date is also served via JSON.
How can I achieve this?
What I did so far:
I created a second variable "options2" with values chart and series.
Then I called
$.getJSON("data/line.php", function(json) {
options.xAxis.categories = json[0]['data'];
options2.series[1] = json[1];
chart = new Highcharts.Chart(options2);
});
But that only shows the first column chart.
Probably you should try use $.merge to prevent object edition.
Try this
$.getJSON("data/column.php", function(json) {
// Merge objects
var newOptions = $.extend({}, options);
// Edit new object instead of old
newOptions.xAxis.categories = json[0]['data'];
newOptions.series[0] = json[1];
chart = new Highcharts.Chart( newOptions );
});
Solved it by passing the series option (chart type) directly via JSON.
I added the "type:line" to the data array, which then overrides previously set options within the script tag.

howto use vaxis in google charts materialview

I have been fiddling with a particle photon, posting data to sparkfun.com
To display this data I am trying to use google.visualization. But I cant seem to get the axis behaving as I want it to.
see (but wait a while it is slow): https://www.hanscees.com/photon/charts-data-sparkfunA.html
I want the caxis to show not 1K, but 1010 and so on. here is my code:
function drawChart1() {
var public_key = 'yA0EjKV3owhKNx1NlN3w';
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1},
data: {'lte' : {'timestamp' : 'now - 4 hours'}},
dataType: 'jsonp',
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Pressure');
$.each(results, function (i, row) {
data.addRow([
(new Date(row.timestamp)),
parseFloat(row.hectopascals)
]);
}); // each row
// see https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart#dual-y-charts
var materialOptions = {
chart: { title: 'Barometer Pressure'},
width: 550,
height: 500,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {axis: 'Pressure'}
},
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
Pressure: {label: 'Pressure (Hpa)'}
}
},
vAxis: {format: 'decimal'},
hAxis: {color: '#333', count: 8}
};
var materialChart = new google.charts.Line(ChartDivBaro);
materialChart.draw(data, materialOptions);
}); // results
} // jsondata
unfortunately, most vAxis options simply do not work on material charts...
see --> Tracking Issue for Material Chart Feature Parity #2143
recommend using a core chart instead...
you can use the following option to get the look and feel close to material
theme: 'material'
solved it without material:
var options = {title:'Pressure Outside',
width:550,
height:300,
vAxis: {format: '0'}
};
var chart = new google.visualization.LineChart($('#chart1').get(0));
chart.draw(data, options); // draw data
}); // results

Categories

Resources