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

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

Related

Set single point as active / show point and tooltip in Google line chart

Im currently using a Google line chart to show two lines intercepting each other. I would like to show the data point and if possible the tooltip as well, where the lines are intercepting.
My current solution is to show all points and increase the size for the specific point, but actually I want to keep the functionality of seeing the points when pointing on them.
if (!intercept && oldVal > newVal) {
intercept = true
point = 'point { size: 10; }'
}
data.push([i + 1, oldVal, newVal, point])
it looks like you're on the right track with the point size.
we have to set the pointSize config option to something greater than zero,
in order to be able to set the size in our style column.
but we can use something like --> pointSize: 0.1
to prevent the other points from being visible.
as for the tooltip, we can set the tooltip.trigger option to either...
'selection' or 'both'
tooltip: {
trigger: 'both'
}
then we can use the chart's 'ready' event,
to set the chart's selection
google.visualization.events.addListener(chart, 'ready', function () {
chart.setSelection([{row: intercept, column: 2}]);
});
with the above trigger option, when we set the chart's selection,
the tooltip will automatically appear.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Old');
data.addColumn('number', 'New');
data.addColumn({type: 'string', role: 'style'});
var intercept = null;
var rows = new Array(10);
$.each(rows, function (i) {
var oldVal = i;
var newVal = rows.length - i;
var point = null;
if ((intercept === null) && (oldVal === newVal)) {
intercept = i;
point = 'point { size: 10; }';
}
data.addRow([i + 1, oldVal, newVal, point])
});
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
chart.setSelection([{row: intercept, column: 2}]);
});
chart.draw(data, {
pointSize: 0.1,
tooltip: {
trigger: 'both'
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

google line chart is drawing extra lines

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

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 ?

Categories

Resources