Double Y axis ticks for Google Charts - javascript

I am trying to set ticks for a double y-axis line graph but either the graph wont load, it it loads exactly the same. Any help will be greatly appreciated
Goal is to set Price ticks: [0.002, 0.004. 0.006. 0.008], and Volume increment by lets say 1000
Also having issues with prices for instance being: 0.00242, 0.00521 all showing up as 0.1
<?php
$sql = "SELECT Timestamp, LastPrice, Volume FROM vol";
$result = $dbconnect->query($sql);
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
google.charts.load('current', {'packages':['line', 'corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var button = document.getElementById('change-chart');
var chartDiv = document.getElementById('chart_div');
var data = google.visualization.arrayToDataTable([
['Timestamp','LastPrice','Volume'],
<?php
while($row = mysqli_fetch_assoc($result)){
echo "[ '".$row["Timestamp"]."', ".$row["LastPrice"].", ".$row["Volume"].", ],";
}
echo $row["LastPrice"];
?>
]);
var materialOptions = {
chart: {
},
width: 600,
height: 300,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {axis: 'LastPrice' },
1: {axis: 'BaseVolume'}
},
vAxis: {1: {ticks:[0, 0.002, 0.004, 0.006]} },
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
LastPrice: {label: 'Price'},
BaseVolume: {label: 'Volume'}
}
}
};
function drawMaterialChart() {
var materialChart = new google.charts.Line(chartDiv);
materialChart.draw(data, materialOptions);
button.innerText = 'Classic';
button.onclick = drawClassicChart;
}
drawMaterialChart();
}
</script>

there are several configuration options that aren't supported by Material charts, including...
{hAxis,vAxis,hAxes.*,vAxes.*}.ticks
see --> Tracking Issue for Material Chart Feature Parity
instead, recommend using a Classic chart with the following option...
theme: 'material'
for dual y-axis charts, use the series option to specify the target axis
series: {
1: {
targetAxisIndex: 1,
}
},
use option vAxes, with an e, to specify ticks for each y-axis
vAxes: {
0: {
ticks:[0, 1000, 2000, 3000],
title: 'Last Price'
},
1: {
ticks:[0, 0.002, 0.004, 0.006],
title: 'Base Volume'
}
}
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'},
{label: 'y1', type: 'number'}
],
rows: [
{c:[{v: 'row 0'}, {v: 1800}, {v: 0.00242}]},
{c:[{v: 'row 1'}, {v: 2200}, {v: 0.00521}]},
{c:[{v: 'row 2'}, {v: 2800}, {v: 0.00343}]},
{c:[{v: 'row 3'}, {v: 2800}, {v: 0.00441}]},
{c:[{v: 'row 4'}, {v: 2300}, {v: 0.00532}]}
]
});
var container = document.getElementById('chart');
var chart = new google.visualization.LineChart(container);
chart.draw(data, {
width: 600,
height: 300,
series: {
1: {
targetAxisIndex: 1,
}
},
theme: 'material',
vAxes: {
0: {
ticks:[0, 1000, 2000, 3000],
title: 'Last Price'
},
1: {
ticks:[0, 0.002, 0.004, 0.006],
title: 'Base Volume'
}
}
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

Related

Cusomizing haxis label in google charts

I do have the following function to draw a chart, which represents some value for a given time. The horizontal axis should be the dates an not the numbers (which are important to make the trendline work). How can i achieved that?
chart_data contains of the following
[["Year","accept","error","total"],[{"v":0,"f":"20.09.2018"},1,3,4],
[{"v":1,"f":"21.09.2018"},4,5,9],[{"v":2,"f":"22.09.2018"},0,7,7],
[{"v":3,"f":"24.09.2018"},14,14,28],[{"v":4,"f":"25.09.2018"},2,2,4],
[{"v":5,"f":"26.09.2018"},6,16,22]]
The js function looks like this:
function drawChart(chart_id, chart_title, chart_data) {
var data = google.visualization.arrayToDataTable(
chart_data
);
var options = {
title: chart_title,
hAxis: {
title: 'Datum',
titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0},
trendlines: {
0: {
type: 'polynomial',
degree: 3,
},
1:{
type: 'polynomial',
degree: 3,
},
2:{
type: 'polynomial',
degree: 3,
} } // Draw a trendline for data series 0.
};
var chart = new google.visualization.AreaChart(document.getElementById(chart_id));
chart.draw(data, options);
}
to customize the haxis labels, use option hAxis.ticks
in this case, we can pull the first value from each row to use for our ticks
var chart_data = [
["Year","accept","error","total"],
[{"v":0,"f":"20.09.2018"},1,3,4],
[{"v":1,"f":"21.09.2018"},4,5,9],
[{"v":2,"f":"22.09.2018"},0,7,7],
[{"v":3,"f":"24.09.2018"},14,14,28],
[{"v":4,"f":"25.09.2018"},2,2,4],
[{"v":5,"f":"26.09.2018"},6,16,22]
];
// extract first value from each row
var ticks = chart_data.map(function (row) {
return row[0];
});
ticks.splice(0, 1); // remove column label
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var chart_data = [
["Year","accept","error","total"],
[{"v":0,"f":"20.09.2018"},1,3,4],
[{"v":1,"f":"21.09.2018"},4,5,9],
[{"v":2,"f":"22.09.2018"},0,7,7],
[{"v":3,"f":"24.09.2018"},14,14,28],
[{"v":4,"f":"25.09.2018"},2,2,4],
[{"v":5,"f":"26.09.2018"},6,16,22]
];
// extract first value from each row
var ticks = chart_data.map(function (row) {
return row[0];
});
ticks.splice(0, 1); // remove column label
var data = google.visualization.arrayToDataTable(chart_data);
var options = {
title: 'chart_title',
hAxis: {
ticks: ticks, // custom labels
title: 'Datum',
titleTextStyle: {color: '#333'}
},
vAxis: {minValue: 0},
trendlines: {
0: {
type: 'polynomial',
degree: 3,
},
1:{
type: 'polynomial',
degree: 3,
},
2:{
type: 'polynomial',
degree: 3,
}
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<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>

Google area chart empty page with data from JSON

I am working on a KPI dashboard, my database contains hot water (hwater) usage per month(adate), comparing this year with last year as an area chart.
However when I run this report my webpage is blank. I have tried setting google.visualization.arrayToDataTable to .DataTable while declaring the column names and also tried with server side AJAX with no success.
Area_Chart.php
<?php
require_once ("connect.php");
//fetch table rows from mysql db
$query = $handler->query("
SELECT MONTH(adate) as month,
MAX(case when YEAR(adate) = YEAR(CURRENT_DATE)-1 THEN hwater ELSE 0 END) as 'Last_Year',
MAX(case when YEAR(adate) = YEAR(CURRENT_DATE) THEN hwater ELSE 0 END) as 'This_Year'
FROM utlt
WHERE YEAR(adate) = YEAR(CURRENT_DATE)-1 OR year(adate) = YEAR(CURRENT_DATE)
GROUP BY MONTH(adate)
ORDER BY MONTH(adate)");
$query->execute();
$results=$query->fetchAll(PDO::FETCH_NUM);
$json=json_encode($results);
//echo $json;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[ {label: 'Year', id: 'month'},
{label: 'Last_Year', id: 'Last_Year', type: 'number'},
{label: 'This_Year', id: 'This_Year', type: 'number'}],
<?=$json?>
], false);
var options = {
isStacked: 'absolute',
title: 'Hot Water Useage',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 100%; height: 500px;"></div>
</body>
</html>
Output of echo $json:
[["1","1.671","21.269"],["2","3.810","22.017"],["3","5.554","24.045"],["4","6.930","25.036"],["5","8.845","27.116"],["6","11.793","28.058"],["7","13.244","28.996"],["8","14.471","30.342"],["9","16.260","30.977"],["10","17.199","31.923"],["11","18.494","33.155"],["12","19.563","33.797"]]
I notice above that hwater from utlt are rapped in "", does this mean its a string? The field type is actually a decimal (6,3).
hwater from utlt being wrapped in "" is definitely a problem,
since the column type is 'number'
try using JSON_NUMERIC_CHECK to encode the json
$json=json_encode($results, JSON_NUMERIC_CHECK);
EDIT
think i found the problem here...
var data = google.visualization.arrayToDataTable([
[ {label: 'Year', id: 'month'},
{label: 'Last_Year', id: 'Last_Year', type: 'number'},
{label: 'This_Year', id: 'This_Year', type: 'number'}],
<?=$json?> // <-- problem
], false);
the problem is the outer array wrapping the row arrays
//--> [[1,1.671,21.269]...
given where <?=$json?> is placed, the rows shouldn't be wrapped in array
this can easily be corrected by using the addRows method to load the json
remove json from arrayToDataTable
var data = google.visualization.arrayToDataTable([
[ {label: 'Year', id: 'month', type: 'number'},
{label: 'Last_Year', id: 'Last_Year', type: 'number'},
{label: 'This_Year', id: 'This_Year', type: 'number'}],
]);
then add another statement for the addRows method, which needs the outer array
data.addRows(
<?=$json?>
);
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
[ {label: 'Year', id: 'month', type: 'number'},
{label: 'Last_Year', id: 'Last_Year', type: 'number'},
{label: 'This_Year', id: 'This_Year', type: 'number'}],
]);
data.addRows(
[[1,1.671,21.269],[2,3.810,22.017],[3,5.554,24.045],[4,6.930,25.036],[5,8.845,27.116],[6,11.793,28.058],[7,13.244,28.996],[8,14.471,30.342],[9,16.260,30.977],[10,17.199,31.923],[11,18.494,33.155],[12,19.563,33.797]]
);
var options = {
isStacked: 'absolute',
title: 'Hot Water Useage',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Charts Legend Position Not Working

This is driving me nuts. I can't get the legend to move at all. This produces a chart with the legend in it's default location on the right.
I clearly have legend position declared as "bottom" but it's not working. Yet this is exactly what the docs say.
google.charts.load('current',{'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff(){
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Count');
data.addColumn('number', 'Variance');
data.addRows([
['Smith', 35, {v: -.1126, f: '-11.26%'} ],
['Chalk', 53, {v: -.0126, f: '-1.26%'} ],
['Hank', 84, {v: -.0252, f: '-2.52%'} ],
['Jordan', 46, {v: .0688, f: '6.88%'} ],
['Bernie', 1, {v: 0, f: '-'} ],
['Ralph', 105, {v: -.0548, f: '-5.48%'} ]
]);
var options = {
series: {
0: {axis: 'Quotes'},
1: {axis: 'Percent'}
},
axes: {
y: {
Quotes: {label: 'Subdmission Count'},
Percent: {label: '% Percent'}
}
},
legend: {
position : 'bottom'
}
};
var table = new google.charts.Bar(document.getElementById('table1'));
table.draw(data, options);
}
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id='table1'></div>
</body>
</html>
legend.position: ['top', 'bottom'] -- are just a couple of the many options that don't work on material charts
see Tracking Issue for Material Chart Feature Parity #2143 for an extensive list
however, these options will work on a core chart...
core --> google.visualization.ColumnChart -- using --> packages: ['corechart']
material --> google.charts.Bar -- using --> packages: ['bar']
there is also an option to get a core chart close to the look & feel of material
theme: 'material'
see following working snippet using core chart instead...
google.charts.load('current',{'packages':['corechart']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff(){
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Count');
data.addColumn('number', 'Variance');
data.addRows([
['Smith', 35, {v: -.1126, f: '-11.26%'} ],
['Chalk', 53, {v: -.0126, f: '-1.26%'} ],
['Hank', 84, {v: -.0252, f: '-2.52%'} ],
['Jordan', 46, {v: .0688, f: '6.88%'} ],
['Bernie', 1, {v: 0, f: '-'} ],
['Ralph', 105, {v: -.0548, f: '-5.48%'} ]
]);
var options = {
chartArea: {
height: '56%'
},
series: {
1: {
targetAxisIndex: 1
}
},
hAxis: {
title: 'Name'
},
vAxes: {
0: {
title: 'Submission Count'
},
1: {
title: '% Percent'
}
},
theme: 'material',
legend: {
position : 'bottom'
}
};
var table = new google.visualization.ColumnChart(document.getElementById('table1'));
table.draw(data, options);
}
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id='table1'></div>
</body>
</html>
{position: 'left'} works fine in your example, so the only option left is that 'bottom' this is not supported.
Similar discussion on guthub mentions that it is not supported for another chart type and not planned to be implemented: https://github.com/google/google-visualization-issues/issues/1964

How to make bars of different color in google charts?

I have the following code which generates a column chart.
<script type="text/javascript">
//google.charts.load('current', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawBar);
function drawBar() {
var data = google.visualization.arrayToDataTable([
['Number of Visits', 'Average Check Size',{ role: 'style' }],
['8+', 26.22, '#083874'],
['4-7', 30.34,'#94CAFC'],
['2-3', 24.09,'#EBBA25'],
['1', 27.95,'#F59E47']
]);
var formatter = new google.visualization.NumberFormat({
fractionDigits: 1,
prefix: '$'
});
formatter.format(data, 1);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" }]);
var options = {
//chartArea: {width: '50%'},
hAxis: {
title: 'Average Check Size',
titleTextStyle: {italic: false},
minValue: 0,gridlines: { color: 'transparent'}
},
vAxis: {
minValue: 0,
title: 'Number of Visits',
titleTextStyle: {italic: false},
gridlines: { color: 'transparent'}},
//colors: ['red','green','blue','yellow'],
legend: {position: 'none'},
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_bar'));
chart.draw(view, options);
}
The output is a column chart with annotations on each of the bars. I want to have a similar kind of output but all four bars must have different colors. How do I do that? Please suggest
You can use the style role. There are examples on google charts page. And here is a jsfiddle.
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }],
['Copper', 8.94, '#b87333'], // RGB value
['Silver', 10.49, 'silver'], // English color name
['Gold', 19.30, 'gold'],
['Platinum', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
]);

Categories

Resources