I've got the following column chart and I'd like to position annotations for positive values above and for negative ones bellow columns. How to do that?
Additional question for values and annotation formatting - how to achieve the formatting of annotations (values above and bellow columns) like vAxis?
google.charts.load('current',{callback:drawChart,'packages':['corechart'],'language':'hr'});
function drawChart()
{
var data = new google.visualization.DataTable();
data.addColumn('date','Datum');
data.addColumn('number','Vrijednost');
data.addColumn('number','Pred. prema preth. 5 dana');
data.addColumn('number','Pred. prema preth. 10 dana');
data.addColumn('number','Relativna promjena');
data.addRows([
[new Date('2017-08-03'),12.10260,12.09797,12.148753333333,0.3199602122016],
[new Date('2017-08-02'),12.06400,12.16005,12.176186666667,-0.69882870054079],
[new Date('2017-08-01'),12.14890,12.12988,12.160606666667,0.3129386508133],
[new Date('2017-07-31'),12.11100,12.13091,12.14988,-0.001651364026678],
[new Date('2017-07-28'),12.11120,12.1175,12.116093333333,0.11821210392746],
[new Date('2017-07-27'),12.09690,12.10942,12.079293333333,0.24113757271416],
[new Date('2017-07-26'),12.06780,12.10184,12.040733333333,0],
[new Date('2017-07-25'),12.06780,12.06525,11.992986666667,0.28753781205331],
[new Date('2017-07-24'),12.03320,12.02595,11.95908,0.18983547592086],
[new Date('2017-07-21'),12.01040,11.95357,11.932006666667,0.41468798073707],
[new Date('2017-07-20'),11.96080,11.9183,11.9194,0.1951832460733],
[new Date('2017-07-19'),11.93750,11.89151,11.914186666667,0.21154604904174],
[new Date('2017-07-18'),11.91230,11.89439,11.937766666667,0.1235543302851],
[new Date('2017-07-17'),11.89760,11.93811,11.967046666667,-0.36595680537295],
[new Date('2017-07-14'),11.94130,11.95136,11.972373333333,0.068716427416171],
[new Date('2017-07-13'),11.93310,11.96335,11.975713333333,-0.1848567987152],
[new Date('2017-07-12'),11.95520,11.94968,11.96142,-0.070212979370754],
[new Date('2017-07-11'),11.96360,11.95871,11.944226666667,0.19429834846403],
[new Date('2017-07-10'),11.94040,11.9698,11.93224,0.099761076413629],
[new Date('2017-07-07'),11.92850,11.96977,11.934313333333,-0.13478894228354],
[new Date('2017-07-06'),11.94460,11.93426,11.931026666667,-0.10036297944233],
[new Date('2017-07-05'),11.95660,11.86036,11.91198,0.66342251932174],
[new Date('2017-07-04'),11.87780,11.86771,11.918093333333,0.048011724968622],
[new Date('2017-07-03'),11.87210,11.88418,11.919446666667,-0.078273604120727],
[new Date('2017-06-30'),11.88140,11.92094,11.907506666667,-0.076531684958581]
]);
var ColumnOpt = {
height: 300,
title: 'Relativna promjena vrijednosti [%]',
annotations: {textStyle: {fontName: 'Tahoma', fontSize: 9}},
vAxis: {textStyle: {fontName: 'Tahoma', fontSize: 9}, format: "#.#'%'",
viewWindow: {min: data.getColumnRange(4).min-0.5}},
hAxis: {textStyle: {fontName: 'Tahoma', fontSize: 9}, showTextEvery: 5},
chartArea: {width: '80%', height: '80%'},
legend: {position: 'none'},
colors: ['purple']
};
var view2 = new google.visualization.DataView(data);
view2.setColumns([0,4,{calc:'stringify',sourceColumn:4,type:'string',role:'annotation'}]);
var container = document.getElementById('Chart2');
var chart2=new google.visualization.ColumnChart(container);
var observer = new MutationObserver(function () {
$.each($('text[text-anchor="start"]'), function (index, label) {
var labelValue = parseFloat($(label).text());
if (labelValue < 0 && $(label).attr('font-height') !== 'bold') {
var bounds = label.getBBox();
var chartLayout = container.getChartLayoutInterface();
$(label).attr('y',chartLayout.getYLocation(labelValue) - bounds.height - 8);
}
});
});
observer.observe(container,{childList: true,subtree: true});
chart2.draw(view2,ColumnOpt);
}
<div id="Chart2"></div>
<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>
several issues to deal with here
on this chart, the annotations have attribute --> text-anchor="middle"
vs. text-anchor="start" on the other
to format the annotations, use a number formatter
var formatAnnotation = new google.visualization.NumberFormat({
pattern: ColumnOpt.vAxis.format
});
use a custom function on the view, vs. predefined "stringify" function
var view2 = new google.visualization.DataView(data);
view2.setColumns([0,4,{
calc: function (dt, row) {
return formatAnnotation.formatValue(dt.getValue(row, 4));
},
type: 'string',
role: 'annotation'
}]);
this poses a problem with commas in the number
need to replace with decimal for parseFloat to handle ok
there is also an issue with annotations overlapping
but this snippet should get you closer...
google.charts.load('current',{callback:drawChart,'packages':['corechart'],'language':'hr'});
function drawChart()
{
var data = new google.visualization.DataTable();
data.addColumn('date','Datum');
data.addColumn('number','Vrijednost');
data.addColumn('number','Pred. prema preth. 5 dana');
data.addColumn('number','Pred. prema preth. 10 dana');
data.addColumn('number','Relativna promjena');
data.addRows([
[new Date('2017-08-03'),12.10260,12.09797,12.148753333333,0.3199602122016],
[new Date('2017-08-02'),12.06400,12.16005,12.176186666667,-0.69882870054079],
[new Date('2017-08-01'),12.14890,12.12988,12.160606666667,0.3129386508133],
[new Date('2017-07-31'),12.11100,12.13091,12.14988,-0.001651364026678],
[new Date('2017-07-28'),12.11120,12.1175,12.116093333333,0.11821210392746],
[new Date('2017-07-27'),12.09690,12.10942,12.079293333333,0.24113757271416],
[new Date('2017-07-26'),12.06780,12.10184,12.040733333333,0],
[new Date('2017-07-25'),12.06780,12.06525,11.992986666667,0.28753781205331],
[new Date('2017-07-24'),12.03320,12.02595,11.95908,0.18983547592086],
[new Date('2017-07-21'),12.01040,11.95357,11.932006666667,0.41468798073707],
[new Date('2017-07-20'),11.96080,11.9183,11.9194,0.1951832460733],
[new Date('2017-07-19'),11.93750,11.89151,11.914186666667,0.21154604904174],
[new Date('2017-07-18'),11.91230,11.89439,11.937766666667,0.1235543302851],
[new Date('2017-07-17'),11.89760,11.93811,11.967046666667,-0.36595680537295],
[new Date('2017-07-14'),11.94130,11.95136,11.972373333333,0.068716427416171],
[new Date('2017-07-13'),11.93310,11.96335,11.975713333333,-0.1848567987152],
[new Date('2017-07-12'),11.95520,11.94968,11.96142,-0.070212979370754],
[new Date('2017-07-11'),11.96360,11.95871,11.944226666667,0.19429834846403],
[new Date('2017-07-10'),11.94040,11.9698,11.93224,0.099761076413629],
[new Date('2017-07-07'),11.92850,11.96977,11.934313333333,-0.13478894228354],
[new Date('2017-07-06'),11.94460,11.93426,11.931026666667,-0.10036297944233],
[new Date('2017-07-05'),11.95660,11.86036,11.91198,0.66342251932174],
[new Date('2017-07-04'),11.87780,11.86771,11.918093333333,0.048011724968622],
[new Date('2017-07-03'),11.87210,11.88418,11.919446666667,-0.078273604120727],
[new Date('2017-06-30'),11.88140,11.92094,11.907506666667,-0.076531684958581]
]);
var ColumnOpt = {
height: 300,
title: 'Relativna promjena vrijednosti [%]',
annotations: {alwaysOutside: true, textStyle: {fontName: 'Tahoma', fontSize: 9}, stem: {length: 4, color: 'transparent'}},
vAxis: {textStyle: {fontName: 'Tahoma', fontSize: 9}, format: "#.#'%'",
viewWindow: {min: data.getColumnRange(4).min-0.5}},
hAxis: {textStyle: {fontName: 'Tahoma', fontSize: 9}, showTextEvery: 5},
chartArea: {width: '80%', height: '80%'},
legend: {position: 'none'},
colors: ['purple']
};
var formatAnnotation = new google.visualization.NumberFormat({
pattern: ColumnOpt.vAxis.format
});
var view2 = new google.visualization.DataView(data);
view2.setColumns([0,4,{
calc: function (dt, row) {
return formatAnnotation.formatValue(dt.getValue(row, 4));
},
type: 'string',
role: 'annotation'
}]);
var container = document.getElementById('Chart2');
var chart2=new google.visualization.ColumnChart(container);
var observer = new MutationObserver(function () {
$.each($('text[text-anchor="middle"]'), function (index, label) {
var labelValue = parseFloat($(label).text().replace(',', '.'));
if (labelValue < 0 && $(label).attr('fill') === '#800080') {
var bounds = label.getBBox();
var chartLayout = chart2.getChartLayoutInterface();
$(label).attr('y',chartLayout.getYLocation(labelValue) + bounds.height);
}
});
});
observer.observe(container,{childList: true,subtree: true});
chart2.draw(view2,ColumnOpt);
}
<div id="Chart2"></div>
<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>
Related
I'm using Google charts Stepped Area in my project, I have 2 data columns (datetime,state).
The problem is when the change in time is dynamic and not fixed the chart gets abnormal like this example, however when the data points are in fixed time change, the chart is drawn correctly for example in this code the points are one every 100 milliseconds.
Example 1 data
['Date', 'State'],
[new Date(1534078983500), 3],
[new Date(1534078983880), 1],
[new Date(1534080441460), 3],
[new Date(1534080441840), 1],
[new Date(1534080533960), 3],
[new Date(1534080534330), 1]
Example 2 data
['Date', 'State'],
[new Date(1534078983100), 3],
[new Date(1534078983200), 1],
[new Date(1534078983300), 3],
[new Date(1534078983400), 1],
[new Date(1534078983500), 3],
[new Date(1534078983600), 1]
according to the Data Format for the SteppedAreaChart,
the Data Type for the x-axis should be --> 'string'
although it may work with dates, the results may be inconsistent
instead, use the DateFormat class to convert the date to a timestamp string
see following working snippet...
here, a DataView is used to create a calculated column for the timestamp...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Date', 'State'],
[new Date(1534078983500), 3],
[new Date(1534078983880), 1],
[new Date(1534080441460), 3],
[new Date(1534080441840), 1],
[new Date(1534080533960), 3],
[new Date(1534080534330), 1]
]);
var formatTime = new google.visualization.DateFormat({
pattern: 'HH:ss.SSSS a'
});
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (dt, row) {
return formatTime.formatValue(dt.getValue(row, 0));
},
label: data.getColumnLabel(0),
type: 'string'
}, 1]);
var options = {
title: 'The decline of \'The 39 Steps\'',
vAxis: {
title: 'Accumulated Rating',
ticks: [{ v: 0, f: '' }, { v: 1, f: 'Close' }, { v: 2, f: 'CLG/OPG' }, { v: 3, f: 'Open' }, { v: 4, f: '' }]
}
};
var chart = new google.visualization.SteppedAreaChart(document.getElementById('chart_div'));
chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
if you need to use the explorer option,
you can use a number instead of a string
use the formatted value to display the actual dates,
and build custom ticks for the x-axis using the same approach...
see following working snippet...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Date', 'State'],
[new Date(1534078983500), 3],
[new Date(1534078983880), 1],
[new Date(1534080441460), 3],
[new Date(1534080441840), 1],
[new Date(1534080533960), 3],
[new Date(1534080534330), 1]
]);
var formatTime = new google.visualization.DateFormat({
pattern: 'HH:ss.SSSS a'
});
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (dt, row) {
return {
v: row,
f: formatTime.formatValue(dt.getValue(row, 0))
};
},
label: data.getColumnLabel(0),
type: 'number'
}, 1]);
var xTicks = [];
for (var i = 0; i < view.getNumberOfRows(); i++) {
addTick(i);
}
function addTick(i) {
xTicks.push({
v: view.getValue(i, 0),
f: view.getFormattedValue(i, 0)
});
}
var options = {
explorer: {},
hAxis: {
ticks: xTicks
},
title: 'The decline of \'The 39 Steps\'',
vAxis: {
title: 'Accumulated Rating',
ticks: [{ v: 0, f: '' }, { v: 1, f: 'Close' }, { v: 2, f: 'CLG/OPG' }, { v: 3, f: 'Open' }, { v: 4, f: '' }]
}
};
var chart = new google.visualization.SteppedAreaChart(document.getElementById('chart_div'));
chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I have produced a dashboard with a date slider that changes what is shown by the graph. I couldn't find a way to sum the total of the columns shown.
https://jsfiddle.net/2uktvcut/
google.charts.load('current', {
'packages': ['corechart', 'controls']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Date", "Total"],
[new Date("1/1/17"), 13],
[new Date("1/2/17"), 15],
[new Date("1/3/17"), 15],
[new Date("1/4/17"), 23],
[new Date("1/5/17"), 51],
[new Date("1/6/17"), 17],
[new Date("1/7/17"), 11],
[new Date("1/8/17"), 18],
[new Date("1/9/17"), 8],
[new Date("1/10/17"), 34],
[new Date("1/11/17"), 13],
[new Date("1/12/17"), 21]
]);
var dashboard = new google.visualization.Dashboard(document.getElementById('marketingChartHolder'));
var dateSlider = new google.visualization.ControlWrapper({
'controlType': 'DateRangeFilter',
'containerId': 'marketingChartControl',
'options': {
'filterColumnLabel': 'Date',
}
});
var stockChart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'marketingChart',
options: {
theme: 'material',
legend: {
position: 'bottom',
},
focusTarget: 'category',
chartArea: {
width: '95%',
height: '90%',
},
width: $(document).width() * 0.98,
height: $(document).height() * .70,
vAxis: {
viewWindow: {
min: 0,
},
},
}
});
google.visualization.events.addListener(stockChart, 'ready', function() {
document.getElementById('png').innerHTML = '<button><a target="_blank" href="' + stockChart.getChart().getImageURI() + '">Get Image</a></button>';
var dt = stockChart.getDataTable();
console.log(dt);
});
dashboard.bind(dateSlider, stockChart);
dashboard.draw(data);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<div id="marketingChartHolder">
<div id="marketingChartControl" style="width: 100%"></div>
<div id="marketingChart"></div>
<div id='png'></div>
<div id="totalHolder">
<p>
Placeholder
</p>
</div>
</div>
I think that I've made a start with stockChart.getDataTable() however I am unsure how to proceed.
After I get the value I plan to use jquery to change the value of the <p>.
you can use the group() method to aggregate the data
see the following working snippet...
google.charts.load('current', {
'packages': ['corechart', 'controls', 'table']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Date", "Total"],
[new Date("1/1/17"), 13],
[new Date("1/2/17"), 15],
[new Date("1/3/17"), 15],
[new Date("1/4/17"), 23],
[new Date("1/5/17"), 51],
[new Date("1/6/17"), 17],
[new Date("1/7/17"), 11],
[new Date("1/8/17"), 18],
[new Date("1/9/17"), 8],
[new Date("1/10/17"), 34],
[new Date("1/11/17"), 13],
[new Date("1/12/17"), 21]
]);
var dashboard = new google.visualization.Dashboard(document.getElementById('marketingChartHolder'));
var dateSlider = new google.visualization.ControlWrapper({
'controlType': 'DateRangeFilter',
'containerId': 'marketingChartControl',
'options': {
'filterColumnLabel': 'Date',
}
});
var stockChart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'marketingChart',
options: {
theme: 'material',
legend: {
position: 'bottom',
},
focusTarget: 'category',
chartArea: {
width: '95%',
height: '90%',
},
width: $(document).width() * 0.98,
height: $(document).height() * .70,
vAxis: {
viewWindow: {
min: 0,
},
},
}
});
google.visualization.events.addListener(dateSlider, 'statechange', calcTotal);
google.visualization.events.addListener(stockChart, 'ready', function () {
document.getElementById('png').innerHTML = '<button><a target="_blank" href="' + stockChart.getChart().getImageURI() + '">Get Image</a></button>';
calcTotal();
});
function calcTotal() {
var dataTotal = google.visualization.data.group(
stockChart.getDataTable(),
[{column: 0, type: 'string', modifier: function () {return 'Total';}}],
[
{
aggregation: google.visualization.data.sum,
column: 1,
label: 'Total',
type: 'number'
}
]
);
var container = document.getElementById('totalHolder');
var table = new google.visualization.Table(container);
table.draw(dataTotal);
}
dashboard.bind(dateSlider, stockChart);
dashboard.draw(data);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<div id="marketingChartHolder">
<div id="marketingChartControl" style="width: 100%"></div>
<div id="marketingChart"></div>
<div id='png'></div>
<div id="totalHolder"></div>
</div>
I have a CSV file with datetime timestamps (in milliseconds from 1970) as X axis separed tis a comma ',' and an associated Temperature value as Y axis.
ie :
1485097200000,22.5
1485098100000,23.8
1485099000000,24.2
etc ...
From that kind of CSV file i would like to generate a google graph code like this :
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
google.load('visualization', '1', {'packages':['annotatedtimeline']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Temperatures');
data.addRows([
[new Date(1485097200000), 22.5],
[new Date(1485098100000), 23.8],
[new Date(1485099000000), 24.2]
]);
var options = {
title: 'Temperature measured every 15 minutes',
width: 900,
height: 500,
hAxis: {
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: 'none'},
minValue: 0
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
var button = document.getElementById('change');
button.onclick = function () {
// If the format option matches, change it to the new option,
// if not, reset it to the original format.
options.hAxis.format === 'M/d/yy' ?
options.hAxis.format = 'MMM dd, yyyy' :
options.hAxis.format = 'M/d/yy';
chart.draw(data, options);
};
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button id="change">Click to change the format</button>
<div id="chart_div"></div>
Would you please tell if it is possible and how i could do it so , i'm newbie.
Regards,
Here is an example for how to get the get the data from a CSV file (in this case come from a string but the principal is the same.
The CSV file should look like this:
1486727700000,5\n1486728600000,7\n1486729200000,3\n1486729800000,1\n1486730400000,3\n1486731000000,4\n1486731600000,3\n1486732200000,4\n1486732800000,4
Also you need to extract the data from the file so here is the function.
function getData(csv) {
var output = [];
csv.split(/\n/).forEach(function(row) {
var cells = row.split(','),
date = new Date(parseInt(cells[0])),
value = parseFloat(cells[1]);
output.push([date, value]);
});
return output;
}
And live demo here:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// google.load('visualization', '1', {'packages':['annotatedtimeline']});
// google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Temperatures');
// data.addRows([
// [new Date(2017, 1, 10, 13, 55), 5], [new Date(2017, 1, 10, 14, 10), 7], [new Date(2017,1, 10,14,20), 3],
// [new Date(2017, 1, 10, 14, 30), 1], [new Date(2017, 1, 10, 14,40), 3], [new Date(2017, 1, 10, 14,50), 4],
// [new Date(2017, 1, 10,15,00), 3], [new Date(2017, 1, 10,15,10), 4], [new Date(2017, 1, 10,15,20), 2]
// ]);
data.addRows(getData(csvFile));
var options = {
title: 'Temperature measured every 15 minutes',
width: 900,
height: 500,
hAxis: {
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: 'none'},
minValue: 0
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
var button = document.getElementById('change');
button.onclick = function () {
// If the format option matches, change it to the new option,
// if not, reset it to the original format.
options.hAxis.format === 'M/d/yy' ? options.hAxis.format = 'MMM dd, yyyy' : options.hAxis.format = 'M/d/yy';
chart.draw(data, options);
};
}
var csvFile = '1486727700000,5\n1486728600000,7\n1486729200000,3\n1486729800000,1\n1486730400000,3\n1486731000000,4\n1486731600000,3\n1486732200000,4\n1486732800000,4';
function getData(csv) {
var output = [];
csv.split(/\n/).forEach(function(row) {
var cells = row.split(','),
date = new Date(parseInt(cells[0])),
value = parseFloat(cells[1]);
output.push([date, value]);
});
return output;
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button id="change">Click to change the format</button>
<div id="chart_div"></div>
http://output.jsbin.com/coxemay
Update
How to get the CSV from file using ajax
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(csvData) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Temperatures');
getData(function(csvData) {
data.addRows(csvData);
var options = {
title: 'Temperature measured every 15 minutes',
width: 900,
height: 500,
hAxis: {
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: 'none'},
minValue: 0
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
var button = document.getElementById('change');
button.onclick = function () {
// If the format option matches, change it to the new option,
// if not, reset it to the original format.
options.hAxis.format === 'M/d/yy' ? options.hAxis.format = 'MMM dd, yyyy' : options.hAxis.format = 'M/d/yy';
chart.draw(data, options);
};
}
function getData(callback) {
$.get('https://gist.githubusercontent.com/moshfeu/e3fd00cb57ae5b5cffbda44422dff112/raw/bcadcdfb5a532cc5711949a60cce639b2da235e6/csv-file', function(csv) {
var output = [];
csv.split(/\n/).forEach(function(row) {
var cells = row.split(','),
date = new Date(parseInt(cells[0])),
value = parseFloat(cells[1]);
output.push([date, value]);
});
callback(output);
});
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id="change">Click to change the format</button>
<div id="chart_div"></div>
http://jsbin.com/coxemay/3/edit?html,js,console
I'm building a column chart using Google Charts. It's a chart that shows the amount of pageviews for a specific page over the last 30 days. I create it with the following JavaScript code (full uncut fiddle here):
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Day');
data.addColumn('number', 'Visits');
data.addRows([
// These data rows come from my database (timestamp + hits)
[new Date(1458691200 * 1000),null],
[new Date(1458777600 * 1000),null],
// This keeps repeating for each day, all with null value
[new Date(1461283200 * 1000),2],
[new Date(1461369600 * 1000),null]
]);
var options = {
chartArea: {
width: '70%',
height: '70%'
},
hAxis: {
format: 'd',
gridlines: {
count: 15
},
title: 'Day'
},
vAxis: {
baseline: 0,
format: '#',
gridlines: {
count: -1
},
title: 'Views',
viewWindowMode:'explicit',
viewWindow: {
max: 10,
min: 0
}
}
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div')
);
chart.draw(data, options);
}
This works pretty well, it comes up with a chart that is close to what I need, but the graph is "zoomed in" on the only not-null data:
This way, it looks like the 2 views of April 22 are actually covering the period of April 12 until April 22, which is not the case.
How do I make the chart prevent from zooming in? Ideally, it should fit itself between the gridlines of the period it is about.
I don't think it is a zoom issue.
Looks like a bug / problem with the 'current' version.
Version '43' renders the expected chart...
google.charts.load('43', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Day');
data.addColumn('number', 'Visits');
data.addRows([
[new Date(1458691200 * 1000),null],
[new Date(1458777600 * 1000),null],
[new Date(1458864000 * 1000),null],
[new Date(1458950400 * 1000),null],
[new Date(1459036800 * 1000),null],
[new Date(1459123200 * 1000),null],
[new Date(1459209600 * 1000),null],
[new Date(1459296000 * 1000),null],
[new Date(1459382400 * 1000),null],
[new Date(1459468800 * 1000),null],
[new Date(1459555200 * 1000),null],
[new Date(1459641600 * 1000),null],
[new Date(1459728000 * 1000),null],
[new Date(1459814400 * 1000),null],
[new Date(1459900800 * 1000),null],
[new Date(1459987200 * 1000),null],
[new Date(1460073600 * 1000),null],
[new Date(1460160000 * 1000),null],
[new Date(1460246400 * 1000),null],
[new Date(1460332800 * 1000),null],
[new Date(1460419200 * 1000),null],
[new Date(1460505600 * 1000),null],
[new Date(1460592000 * 1000),null],
[new Date(1460678400 * 1000),null],
[new Date(1460764800 * 1000),null],
[new Date(1460851200 * 1000),null],
[new Date(1460937600 * 1000),null],
[new Date(1461024000 * 1000),null],
[new Date(1461110400 * 1000),null],
[new Date(1461196800 * 1000),null],
[new Date(1461283200 * 1000),2],
[new Date(1461369600 * 1000),null]
]);
var options = {
chartArea: {
width: '70%',
height: '70%'
},
hAxis: {
format: 'd',
gridlines: {
count: 15
},
title: 'Day'
},
vAxis: {
baseline: 0,
format: '#',
gridlines: {
count: -1
},
title: 'Views',
viewWindowMode:'explicit',
viewWindow: {
max: 10,
min: 0
}
}
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div')
);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
i am trying to create a line chart using google charts libraries.
The data contains, date (x axis), number (col 1), number (col 2), float (col 3).
I want to display two decimals on the 3rd column tooltip while keeping its y axis 0 to 100, this is my current code (running here https://jsfiddle.net/uqh56hsu/1/):
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Hours');
data.addColumn('number', 'col1');
data.addColumn('number', 'col2');
data.addColumn('number', 'percent');
data.addRows([
[new Date(1454950800*1000),0,0,0],[new Date(1454947200*1000),0,0,0],[new Date(1454943600*1000),2,0,0.00],[new Date(1454940000*1000),24,1,4.17],[new Date(1454936400*1000),12,1,8.33],[new Date(1454932800*1000),64,4,6.25],[new Date(1454929200*1000),176,11,6.25],[new Date(1454925600*1000),142,7,4.93],[new Date(1454922000*1000),114,7,6.14],[new Date(1454918400*1000),0,0,0],[new Date(1454914800*1000),0,0,0],[new Date(1454911200*1000),0,0,0],[new Date(1454907600*1000),0,0,0],[new Date(1454904000*1000),0,0,0],[new Date(1454900400*1000),0,0,0],[new Date(1454896800*1000),0,0,0],[new Date(1454893200*1000),0,0,0],[new Date(1454889600*1000),0,0,0],[new Date(1454886000*1000),0,0,0],[new Date(1454882400*1000),0,0,0],[new Date(1454878800*1000),0,0,0],[new Date(1454875200*1000),0,0,0],[new Date(1454871600*1000),180,10,5.56], ]);
var formatter = new google.visualization.NumberFormat({
fractionDigits: 2,
suffix: '%'
});
formatter.format(data, 3);
var options = {
width: 900,
height: 500,
backgroundColor: '#f1f1f1',
colors: ['#ff851b', '#03a9f4', '#8dc859'],
dateFormat: 'H',
vAxes:[
{ titleTextStyle: {color: '#FF0000'}},
{ titleTextStyle: {color: '#FF0000'}, minValue: 0, maxValue: 100, format: '#\'%\'', viewWindowMode : 'explicit', viewWindow:{
max:100,
min:0
}}
],
series:[
{targetAxisIndex:0},
{targetAxisIndex:0},
{targetAxisIndex:1}
]
};
var chart = new google.charts.Line(document.getElementById('linechart_material'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
I've tried adding the formatter code earlier and later in the code, trying to apply it to other columns, etc, nothing seem to work. The 3rd column tooltip always gets the decimals removed.
What am I doing wrong?
The format is being set in the vAxes option, which was overriding the formatter...
Just set the format to --> format: '#,##0.00\'%\''
No need for a formatter here...
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Hours');
data.addColumn('number', 'col1');
data.addColumn('number', 'col2');
data.addColumn('number', 'percent');
data.addRows([
[new Date(1454950800*1000),0,0,0],
[new Date(1454947200*1000),0,0,0],
[new Date(1454943600*1000),2,0,0.00],
[new Date(1454940000*1000),24,1,4.17],
[new Date(1454936400*1000),12,1,8.33],
[new Date(1454932800*1000),64,4,6.25],
[new Date(1454929200*1000),176,11,6.25],
[new Date(1454925600*1000),142,7,4.93],
[new Date(1454922000*1000),114,7,6.14],
[new Date(1454918400*1000),0,0,0],
[new Date(1454914800*1000),0,0,0],
[new Date(1454911200*1000),0,0,0],
[new Date(1454907600*1000),0,0,0],
[new Date(1454904000*1000),0,0,0],
[new Date(1454900400*1000),0,0,0],
[new Date(1454896800*1000),0,0,0],
[new Date(1454893200*1000),0,0,0],
[new Date(1454889600*1000),0,0,0],
[new Date(1454886000*1000),0,0,0],
[new Date(1454882400*1000),0,0,0],
[new Date(1454878800*1000),0,0,0],
[new Date(1454875200*1000),0,0,0],
[new Date(1454871600*1000),180,10,5.56]
]);
var options = {
width: 900,
height: 500,
backgroundColor: '#f1f1f1',
colors: ['#ff851b', '#03a9f4', '#8dc859'],
dateFormat: 'H',
vAxes:[
{
titleTextStyle: {color: '#FF0000'}
},
{
titleTextStyle: {
color: '#FF0000'
},
minValue: 0,
maxValue: 100,
format: '#,##0.00\'%\'', // set format here -- formatter not needed
viewWindowMode : 'explicit',
viewWindow: {
max:100,
min:0
}
}
],
series:[
{targetAxisIndex:0},
{targetAxisIndex:0},
{targetAxisIndex:1}
]
};
var chart = new google.charts.Line(document.getElementById('linechart_material'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="linechart_material"></div>