I am using the Google Visualization API. A chart is generated based on values from an ajax call function drawchart().
The user then inputs values in textboxes and this point is added on the chart also (function addUserPoint()). function addUserPoint2() is autogenerated and is also added onto the map. The result of adduserpoint and adduserpoint2 have a line between them.
My issue: If the user adds a new point again, the chart adds those values and the previously added points stay on the chart. I want to get rid of the results of adduserpoint and adduserpoint2 before adding a new point. How can I achieve this?
var chartData;
var options2;
function addUserPoint() {
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
var aa= $("#wbtotala").text();
var bb= $("#wbtotalb").text();
chartData.addRow([
parseFloat(bb),
null,
parseFloat(aa)
]);
myLineChart.draw(chartData, options2);
}
function addUserPoint2(){
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
myLineChart.draw(0,0, options2);
var aa2 = fweight;
var bb2= fcg;
chartData.addRow([
parseFloat(bb2),
null,
parseFloat(aa2)
]);
myLineChart.draw(chartData, options2);
}
function drawchart() {
document.getElementById('addPoint').addEventListener('click', addUserPoint, false);
document.getElementById('addPoint').addEventListener('click', addUserPoint2, false);
chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Sli');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < chartdatax.length; i++) {
chartData.addRow([parseFloat(chartdatax[i]), parseFloat(chartdatay[i])]);
};
options2 = {
height: 500,
hAxis: {
title: 'AB',
gridlines: {
count: 20
}
},
vAxis: {
title: 'CD',
gridlines: {
count: 15
}
},
chartArea: {top:40, width: "70%", height: "75%"},
legend: { position: 'none' },
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('myChart2'));
myLineChart.draw(chartData, options2);
}
Use the Below Command.Here data is the DataTable Variable.
var data = new google.visualization.DataTable();
Set chartData to an empty object in addUserPoint();
function addUserPoint() {
charData = {};
if (chartData.getNumberOfColumns() === 2) {
...
}
}
This makes sure that anytime you add a new Data, it clears the previous data and you have a fresh new dataset ;)
Related
I have a line chart to draw multi values but it's drawing extra line with angles, I have checked my data there are no duplicates. this is how it looks like :
my chart options are simple:
var options = {
"legend": { "position": "top"},
"hAxis": {
title: "Time of Day"
},
vAxis: {
"textPosition": "out",
textStyle: {color: '#328332'},
title: "Voltage (V)",
titleTextStyle: {color: '#328332'},
}
}
var chartId = 'records-chart';
var dt = new google.visualization.DataTable();
dt.addColumn('datetime', 'Date');
dt.addColumn('number', 'Voltage');
var data = [];
for (var i = 0; i < $scope.data.length; i++) {
data[i] = [
$scope.data[i].time,
$scope.data[i].voltage,
];
}
dt.addRows(data);
var chart = new google.visualization.LineChart(document.getElementById(chartId));
chart.draw(rtRecordsDataTable, options);
why is the chart connecting data in this weird behaviour ? what can I do to avoid it?
looks like you need to sort the data by the first column (date),
before drawing the chart...
dt.addRows(data);
dt.sort([{column: 0}]);
var chart = new google.visualization.LineChart(document.getElementById(chartId));
chart.draw(rtRecordsDataTable, options);
Actually, I am facing related to the Google charts while implementing with Dynamic data. Here the issue When ever I am clicking a tab that particular data has to be displayed in Chart.Suppose Say like Clicking the current Day is displaying the below result in chart
After pressing on the tab say after pressing Last week it is not displaying chart correctly in chart area
Suppose if u press again Current Day the char is displayed like this
Here the chart area is not working properly after having first click and second click
`google.charts.load('current', { 'packages': ['bar'] });
$('#t1').click(function () {
google.charts.setOnLoadCallback(BarC);
function BarC() {
var jsonData = $.ajax({
type: 'GET',
url: xxxx.xxxx.xxxx,
dataType: 'json',
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'data1');
data.addColumn('number', 'data2');
data.addColumn('number', 'data3');
data.addColumn('number', 'data4');
data.addRows(results.length);
for (i = 0; i < results.length; i++) {
data.setValue(i, 0, results[i]["data1"]);
data.setValue(i, 1, parseInt(results[i]["data2"]));
data.setValue(i, 2, parseInt(results[i]["data3"]));
data.setValue(i, 3, parseInt(results[i]["data4]));
}
var options = {
backgroundColor: 'transparent',
bars: 'vertical',
chartArea: { left: 0, top: 0, width: '100%', height: '100%' }// Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('chart'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
);
}
});`
Try
google.charts.setOnLoadCallback(function() {
$('#t1').click(function () {
// ...
});
$('#t2').click(function () {
// ...
});
// ...
});
https://embed.plnkr.co/19CellQvdGZTjzf9hikU/
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();
}
}
I am trying to work with google charts for the first time. My Json is as below
{\"cols\":[{\"id\":\"Date\",\"label\":\"Date\",\"type\":\"date\"},{\"id\":\"KeywordCount\",\"label\":\"count\",\"type\":\"number\"}],\"rows\":[{\"c\":
[{\"v\":\"new Date(2014725)\",\"f\":\"25 July 2014\"},{\"v\":\"77\",\"f\":\"77\"}]},{\"c\":
[{\"v\":\"new Date(2014724)\",\"f\":\"24 July 2014\"},{\"v\":\"101\",\"f\":\"101\"}]},{\"c\":
[{\"v\":\"new Date(2014723)\",\"f\":\"23 July 2014\"},{\"v\":\"100\",\"f\":\"100\"}]},{\"c\":
[{\"v\":\"new Date(2014722)\",\"f\":\"22 July 2014\"},
{\"v\":\"130\",\"f\":\"130\"}]}],\"p\":null}
This looks good for me, I am not able to figured it out what i am missing because i can only see an error in the chart ("undefined is not a function") . My javascript file for Google charts are
google.load('visualization', '1', { 'packages': ['corechart'] });
var postDate = $('#ReportingWall').serialize();
function drawChartAll() {
var jsonData = $.ajax({
url: '/ReportingWall/analyseStats/',
type: 'POST',
data: postDate,
dataType: 'json',
async: false,
success: function (response) {
}
}).responseText;
var data = new google.visualization.DataTable(jsonData);
console.debug(jsonData);
console.debug(data);
var chart = new google.visualization.LineChart(document.getElementById('charts_all'));
chart.draw(data, options);
var columns = [];
var series = {};
for (var i = 0; i < data.getNumberOfColumns() ; i++) {
columns.push(i);
if (i > 0) {
series[i - 1] = {};
}
}
var options = {
title: 'Keywords:',
width: 908,
legend: {
position: 'right'
},
legendFontSize: 14,
chartArea: {
left: 50,
width: '80%'
},
series: series
}
google.visualization.events.addListener(chart, 'select', function () {
var sel = chart.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 (columns[col] == col) {
// hide the data series
columns[col] = {
label: data.getColumnLabel(col),
type: data.getColumnType(col),
calc: function () {
return null;
}
};
// grey out the legend entry
series[col - 1].color = '#CCCCCC';
} else {
// show the data series
columns[col] = col;
series[col - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
}
});
}
When using dates in the DataTable JSON structure, you must omit the new keyword; you are constructing a string that the Visualization API will parse into a Date object, not constructing a Date object itself.
{
"cols":[
{"id":"Date","label":"Date","type":"date"},
{"id":"KeywordCount","label":"count","type":"number"}
],
"rows":[
{"c":[{"v":"Date(2014725)","f":"25 July 2014"},{"v":77,"f":"77"}]},
{"c":[{"v":"Date(2014724)","f":"24 July 2014"},{"v":101,"f":"101"}]},
{"c":[{"v":"Date(2014723)","f":"23 July 2014"},{"v":100,"f":"100"}]},
{"c":[{"v":"Date(2014722)","f":"22 July 2014"},{"v":130,"f":"130"}]}
],
"p":null
}
If you clean it up a bit you can see in the last row you have a useless " as last char
{"cols":[
{"id":"Date","label":"Date","type":"date"},
{"id":"KeywordCount","label":"count","type":"number"}],
"rows":[
{"c":[{"v":"new Date(2014725)","f":"25 July 2014"},{"v":"77","f":"77"}]},
{"c":[{"v":"new Date(2014724)","f":"24 July 2014"},{"v":"101","f":"101"}]},
{"c":[{"v":"new Date(2014723)","f":"23 July 2014"},{"v":"100","f":"100"}]},
{"c":[{"v":"new Date(2014722)","f":"22 July 2014"},{"v":"130","f":"130"}]}],
"p":null}"
also start with a sample similar of PHP
OR this ajax
http://www.santarosa.edu/~jperetz/projects/ajax-json/