google line chart is drawing extra lines - javascript

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);

Related

Hide Slice in Google Donut Chart

I am using Google Donut Chart.
In my case, sometime I will have below data
{
DATA_1: 10,
DATA_2: 15,
INVALID_DATA: 10000000 (Big Number)
}
In such case, my valid data is showing very thin or slice not visible in Charts.
Is there any option in Google Charts to hide particular Slice to make visible other slices better?
I want valid data to show percentage with INVALID_DATA, but just hiding the INVALID_DATA Slice.
there are no options on the chart itself, but hiding a slice can be done with a DataView
but cannot avoid skewing the size of the remaining slices,
relative to the hidden slice
in the following example, a column is added to calculate the % with the hidden slice
then the option pieSliceText: 'value' is used to show the true %
a DataView is used to hide the original value column, and the row with the big slice
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Data Type', 'Value'],
['DATA_1', 10],
['DATA_2', 15],
['INVALID_DATA', 10000000]
]);
var options = {
pieHole: 0.4,
pieSliceText: 'value',
theme: 'maximized',
height: 262,
width: 262,
};
// get total -- sum
var dataGroup = google.visualization.data.group(
data,
[{column: 0, type: 'string', modifier: function () {return '';}}],
[{column: 1, type: 'number', aggregation: google.visualization.data.sum}]
);
var hideRows = [];
data.addColumn({type: 'number', label: '%'});
for (var i = 0; i < data.getNumberOfRows(); i++) {
// set % value
data.setValue(i, 2, data.getValue(i, 1) / dataGroup.getValue(0, 1));
// hide big #
if (data.getValue(i, 2) > .99) {
hideRows.push(i);
}
}
var numberFormat = new google.visualization.NumberFormat({
pattern: '#,##0.00000 %'
});
numberFormat.format(data, 2);
var dataView = new google.visualization.DataView(data);
dataView.hideColumns([1]);
dataView.hideRows(hideRows);
var pieChart = new google.visualization.PieChart(document.getElementById('pieChart_div'));
pieChart.draw(dataView, options);
var tableChart = new google.visualization.Table(document.getElementById('tableChart_div'));
tableChart.draw(data);
},
packages: ['corechart', 'table']
});
div {
padding: 2px 2px 2px 2px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="pieChart_div"></div>
<div id="tableChart_div"></div>

How to clear chart before adding new data?

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 ;)

Google Column Chart - Show different color for each column

Snippet
google.load("visualization", "1", {packages: ["corechart", "bar"]});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var timesheetRes = ["Resouce 1","Resouce 2","Resouce 3","Resouce 4","Resouce 5"];
var timesheetWeek = ["Week 1","Week 2","Week 3","Week 4","Week 5"];
var timesheetHours = [45,40,40,0,0];
var dataArray = [['Resources', 'Week', 'Hours']];
for (var n = 0; n < timesheetHours.length; n++) {
dataArray.push([timesheetRes[n], timesheetWeek[n], timesheetHours[n]]);
}
var data = new google.visualization.arrayToDataTable(dataArray);
var color = <?php echo $json_color_str ?>;
var color_count = <?php echo $color_count ?>;
for (var i = 0; i < color_count; i++) {
var color_str = color[i];
var options = {
width: 700,
height: 350,
legend: {position: 'none'},
bar: {groupWidth: '50%'},
isStacked: true,
tooltip: {trigger: 'none'},
colors: color_str, //being passed in array format for each bar
hAxis: {title: "Resource(s)",
titleTextStyle: {color: '#e91e63', bold: 1, fontSize: 14}},
vAxis: {title: "Week(s)",
ticks: weekAxis(),
gridlineColor: 'transparent',
titleTextStyle: {color: '#F4B400', bold: 1, fontSize: 14}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById("top_x_div"));
chart.draw(data, options);
}
}
function weekAxis() {
var ticks = new Array();
var week_count = <?php echo $week_no ?>; //count number of weeks
for (i = 1; i <= week_count; i++) {
var tick_str = {};
tick_str['v'] = (week_count * i);
tick_str['f'] = 'Week ' + i;
ticks.push(tick_str);
}
return ticks;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="top_x_div"></div>
Current Output
Expected Output
where Week(s) will be displayed on vAxis while Resource(s) will be displayed on hAxis. Here I have changed hAxis and vAxis values to display Weeks and
Resources respectively and show fix 4/5/6 chart sections considering number of weeks in a month.
Tried looping options by passing color array for each bar, but it only takes the last array passed and thus displays same color for each and its columns.
How can I change color of chart columns based on color string
passed as shown in expected output image ?
Or is it possible using jQuery ?

Google Charts - how to add a fixed scale on an axis

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,
},
}
};

How I can have different values and different labels at graphael?

I am using a linechart at graphael. My datapoints are dates,which are not recognisable by the graphael. So I have represented every date, using 1,2,3 ....
The fact is that I need to display dates at my chart, as the x axis labels. How I can do that? I tried the label property, but it does not working.
My code is shown below:
var lines = r.linechart(30, 30, 600, 440,[[1,2,3,4,5]],[[100,150,130,85,100]], {axisxstep : 20,nostroke: false, axis: "0 0 1 1", symbol: "circle", smooth: true }).hoverColumn(function () {
this.tags = r.set();
for (var i = 0, ii = this.y.length; i < ii; i++) {
this.tags.push(r.tag(this.x, this.y[i], this.values[i], 160, 10).insertBefore(this).attr([{ fill: "#fff" }, { fill: this.symbols[i].attr("fill") }]));
}
}, function () {
this.tags && this.tags.remove();
});
Take a look at this fiddle. You have to change the attribute of each label (date for us) inside chartobject:
var lineChart = r.linechart(0, 0, 200, 250, xValues, yValues1, {
smooth: true,
colors: ['#F00', '#0F0', '#FF0'],
symbol: 'circle',
axis: '0 0 1 1'
});
for (var i = 0; i < lineChart.axis[0].text.items.length; i++) {
var label = lineChart.axis[0].text.items[i];
var originalDate = new Date(parseInt(label.attr('text'), 10));
var newText = originalDate.getDate() + "/" + (originalDate.getMonth() + 1) + "/" + (originalDate.getFullYear());
label.rotate(60);
label.attr({
'text': newText
});
}
Also, the data for graphael can only be numerical type to plot the graph, we have to create a Date object for each label in x like this:
var xValues = [
new Date("01/05/2014"),
new Date("01/06/2014"),
new Date("01/07/2014"),
new Date("01/08/2014"),
new Date("01/09/2014"),
new Date("01/10/2014"),
new Date("01/11/2014"),
new Date("01/12/2014"),
new Date("01/13/2014")
];

Categories

Resources