Issue when using ticks option on h-axis: google charts - charts

I am using google chart's combo stacked bar. I want to display explicit values for h-axis, so I used ticks option. But, after using this option, my graph is displaying all bar values at once along the h-axis. But, I want to limit the bars to let's say 5 at a time and display the rest dynamically by sliding the charRangeFilter. The bars are almost appearing as straight lines when I use ticks option as shown in the image. Could some help me in resolving this issue? Any help is highly appreciated
Below is the code for the chart options
let hTicks = new Array<Date>(); // I already populated this array with Dates
let chart = new google.visualization.ChartWrapper({
'chartType': 'ComboChart',
'containerId': 'chartRangeFilter_chart_div',
'options': { .
// Use the same chart area width as the control for . axis alignment.
'width': '100%',
'height': '100%',
'hAxis': { 'title': 'DATES', 'gridlines': { 'color': 'transparent' }, 'ticks': hTicks, 'slantedText': true, 'slantedTextAngle': hTicks.length <= 10 ? 45 : 90 },
'legend': 'none',
'vAxis': { 'title': 'CABINS', 'viewWindow': { 'min': 0, 'max': (Number(cabinTotal) * 1.5) } },
'seriesType': 'bars',
'chartArea': { 'height': '50%', 'width': '85%' },
'bar': { 'groupWidth': '15%' },
'series': { 4: { 'type': 'line' } },
'isStacked': true,
'colors': ['#95d631', '#d7d7d7', '#f44336', '#00bcd4', '#ffc107']
}
Below are the charts
Chart with Tick option Chart Without Tick option

Solved by updating the ticks dynamically as the user slides the chartFilter

Related

Adding Variation to a Standard Google Bar Chart

I'm using a standard bar chart based on Google's code description
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
},
bars: 'horizontal' // Required for Material Bar Charts.
};
The problem is that I have more data, like the variation in Sales in 2014, that I would like to get included in the chart = maybe as whisker lines or an additional number that overlay when you mouseover a bar. Is this even possible? If so, how is it done?
It turns out you can do this (it's a bit more complicated with html because you have to find the classic graph options)
add specific tooltip to arraytoDataTable

Highcharts custom error handler

We are using highcharts to plot multiple charts on a single HTML page.
However one/some of the chart throw highchart error and we like to capture those error and show different error to user.
For this highcharts do provide custom error handler. But this custom error handler does not provide information about specific chart throwing that error.
Here that JS Fiddle provided by highcharts, which works fine for a chart :
Highcharts.error = function (code, true) {
// See
https://github.com/highcharts/highcharts/blob/master/errors/errors.xml
// for error id's
Highcharts.charts[0].renderer
.text('Chart error ' + code)
.attr({
fill: 'red',
zIndex: 20
})
.add()
.align({
align: 'center',
verticalAlign: 'middle'
}, null, 'plotBox');
};
http://jsfiddle.net/gh/get/library/pure/highslide-software/highcharts.com/tree/master/samples/highcharts/chart/highcharts-error/
Any idea how can I use this custom error handler per chart?
I'm using new Highcharts.Charts(options) to create new chart, but don't see way to specify error handler per chart.
Additional info: Charts are refreshed/appended using data through APIs. User that configures chart also configures refresh interval and query to use for chart.
Error handling in HighCharts does not make much sense. It would make more sense to pass the chart instance to Highcharts.error (like Kamil Kulig wrote) or to have an error event in chart.events. Anyways
here is a solution I came up with:
Create an array of errors:
var chartErrors = [];
Create an error handler which will push errors into the chartErrors. Error objects I'm making look like this: {"chartIndex": <chart index>, "errorCode": <error code>}. All charts are added to the Highcharts.charts array when they are created so we can use Highcharts.charts.length - 1 for the chartIndex.
Highcharts.error = function (code) {
// See https://github.com/highcharts/highcharts/blob/master/errors/errors.xml
// for error id's
chartErrors.push({"chartIndex": Highcharts.charts.length - 1, "errorCode":code});
};
After initiating all charts we will have an array of errors. We can call forEach on this array and handle errors the way we want.
chartErrors.forEach(function(c) {
Highcharts.charts[c.chartIndex].renderer
.text('Chart error ' + c.errorCode)
.attr({
fill: 'red',
zIndex: 20
})
.add()
.align({
align: 'center',
verticalAlign: 'middle'
}, null, 'plotBox');
});
Working example:
Note: I've wrapped the code in a self invoking function to prevent leaking variables to global scope.
(function() {
var chartErrors = [];
Highcharts.error = function (code) {
// See https://github.com/highcharts/highcharts/blob/master/errors/errors.xml
// for error id's
chartErrors.push({"chartIndex": Highcharts.charts.length - 1, "errorCode":code});
};
Highcharts.chart('container1', {
title: {
text: 'Demo of Highcharts error handling'
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May']
},
yAxis: {
type: 'logarithmic',
min: 0
},
series: [{
data: [1, 3, 2],
type: 'column'
}]
});
Highcharts.chart('container2', {
title: {
text: 'Solar Employment Growth by Sector, 2010-2016'
},
subtitle: {
text: 'Source: thesolarfoundation.com'
},
yAxis: {
title: {
text: 'Number of Employees'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2010
}
},
series: [{
name: 'Installation',
data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
}, {
name: 'Manufacturing',
data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434]
}, {
name: 'Sales & Distribution',
data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387]
}, {
name: 'Project Development',
data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
}, {
name: 'Other',
data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111]
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
Highcharts.chart('container3', {
title: {
text: 'Demo of Highcharts error handling'
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May']
},
yAxis: {
type: 'logarithmic',
min: 0
},
series: [{
data: [1, 3, 2],
type: 'column'
}]
});
chartErrors.forEach(function(e) {
Highcharts.charts[e.chartIndex].renderer
.text('Chart error ' + e.errorCode)
.attr({
fill: 'red',
zIndex: 20
})
.add()
.align({
align: 'center',
verticalAlign: 'middle'
}, null, 'plotBox');
});
})();
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container1" style="height: 400px"></div>
<div id="container2" style="height: 400px"></div>
<div id="container3" style="height: 400px"></div>
Highcharts error function is not adjusted to have a chart context as an argument, because it can be executed in different contexts too.
For example: error number 16 occurs when Highcharts/Highstock is loaded second time in the same page. It has nothing to do with the chart, because it depends on script importing only.
The workaround I found requires some searching and and a little bit of coding.
Refer to this live demo: http://jsfiddle.net/kkulig/a8nun9aL/
I found the place in the code responsible for throwing the error 10 (the one you used in your example). I overwrote this function (see this doc page for more information about overwriting in Highcharts: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts) and added a chart variable (from Highcharts.Axis.prototype.setTickInterval scope) as the third argument:
if (
axis.positiveValuesOnly &&
!secondPass &&
Math.min(axis.min, pick(axis.dataMin, axis.min)) <= 0
) { // #978
H.error(10, 1, chart); // Can't plot negative values on log axis // MODIFIED LINE
}
It should be done for all errors you want to custom handle.
Now it can be used in custom Highcharts.error function:
Highcharts.error = function(code, stop, chart) {
// See https://github.com/highcharts/highcharts/blob/master/errors/errors.xml
// for error id's
Highcharts.charts[0].renderer
.text('Chart error ' + code + " on chart titled: " + chart.title.textStr)
(...)
You can add your own property in chart constructor options and find it in chart.options object.

Google Charts area chart custom tooltip not working as expected

I'm trying to add tooltips to a Google Area Chart, but I'm getting unexpected behavior. I took the Area Chart JSFiddle example and modified it to add a custom tooltip as described here. My content looks like this:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', { type: 'string', role: 'tooltip'}],
['2013', 1000, 400, 'wtf'],
['2014', 1170, 460, 'hithere'],
['2015', 660, 1120, 'doh'],
['2016', 1030, 540, 'moohaha']
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0},
focusTarget: 'category'
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
JSFiddle here: https://jsfiddle.net/accelerate/y18tb8eq/
Rather than replacing the entire tooltip content, like I expected, the 'expenses' line in the tooltip gets replaced with my tooltip data. For example, the tooltip for the first set of data looks like:
2013
Sales: 1,000
Expenses: wtf
Can someone explain to me what I'm doing wrong?
I figured it out. Which column the tooltip is in matters. I needed to put the tooltip column immediately after the first column. So my header column has to look like this:
['Year', { type: 'string', role: 'tooltip'}, 'Sales', 'Expenses']

Google charts multiline dynamic charts

Am new to PHP coding & have a few google charts working. All of these charts I've generated so far are based on (date,number of event occurrences) type of chart. I'm trying to plot a google chart whose data is the output of SQL query.
The output of SQL query looks as below
|SERIES|DATE_1|DATE_2|DATE_3|
|a|2|3|
|b|4|6|
|c|7|8|
Both SERIES & DATE_1 can vary. That is to say, based on various conditions in the SQL query, the number of DATE_ can be vary & so can the SERIES.
I would then have to pass this output to the google chart plot code.
Here is what i've tried coding so far
$link = mysql_connect("localhost", "user", "pass");
$dbcheck = mysql_select_db("database");
if ($dbcheck) {
$chart_array_1[] = "['MY_DATE','MY_NAME','#NUM_OCCURENCES']";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$my_date=$row["MY_DATE"];
$my_ins=$row["MY_NAME"];
$my_count=$row["MY_COUNT"];
$chart_array_1[]="['".$my_date."','".$my_ins."',".$my_count."]";
}
}
}
mysqli_close($link);
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data_1 = google.visualization.arrayToDataTable([<?php echo (implode(",", $chart_array_1)); ?>])
var options = {
bar: {groupWidth: "6%"},
trendlines: {
1: {
type: 'linear',
color: 'green',
lineWidth: 3,
opacity: 0.3,
showR2: true,
visibleInLegend: true
}
},
chartArea: {
left: 70,
top: 61,
width:'95%',
height:'70%'
},
curveType: 'function',
//width: 1600,
height: 400,
pointSize: 4,
lineWidth: 2,
visibleInLegend: false,
vAxis: {
//title: "GC#",
logScale: true,
titleTextStyle: {
color: 'black'
}
},
hAxis: {
title: "TIMELINE",
titleTextStyle: {
bold: false,
color: 'black'
}
},
legend: {
position: 'top',
alignment: 'center',
textStyle: {
color: 'blue'
}
}
};
var chart_1 = new google.visualization.LineChart(document.getElementById('plot1'));
chart_1.draw(data_1, options);
}
</script>
I'm unable to plot the graph. I get the error "Data column(s) for axis #0 cannot be of type stringĂ—". Could someone please help me here.
I'd like to see a,b,c etc as separate series each while the date goes on to the X-Axis. Please note am after generating data dynamically using SQL query & not a static array which most examples demonstrate. Could someone please help?
Managed to implement thing a different way. Hence this question can be ignored.

can't hide the tooltip (equation) on the trendline on a google chart

can you please help me hide the tooltip (equation) on the trendline on the google chart on this page ?
Thanks
Here are the chart options I am using :
var options = {
title: 'Weight of pro surfer vs. Volume of his pro model',
hAxis: {title: 'Weight (kg)', minValue: 53, maxValue: 100}, //55
vAxis: {title: 'Volume (l)'}, //, minValue: 20, maxValue: 40}, //20
legend: 'none',
colors: ['#000000'],
series: {
1: { color: '#06b4c8' },
2: { color: '#575e6a' }
},
legend: {position: 'top right', textStyle: {fontSize: 8}},
chartArea: {width: '60%'},
//tooltip:{trigger:'none'}, //it hides all tooltips on the whole graph
trendlines: { 0: {//type: 'exponential',
visibleInLegend: true,
color: 'grey',
lineWidth: 2,
opacity: 0.2,
tooltip:{trigger:'none'}, //does nothing
labelInLegend: 'Linear trendline\n(Performance)'
}
} // Draw a trendline for data series 0.
};
If I add tooltip:{trigger:'none'}, before trendlines it hides the tooltips of the whole graph.
It has been implemented but not documented yet:
trendlines: {0: {tooltip: false}}
Only solution I was able to make is replacing the text of the tooltips from trendline. This example makes use of jquery, so if you are able to use jquery you can use:
google.visualization.events.addListener(chart, 'onmouseover', function(e){
$('svg *:contains("* x")').each(function(){
$(this).text('')
})
})
If not, it should be possible to replicate with pure js, but that´s the main idea: find the tooltips that have the formula attached, and replace the text with nothing
Here is a working example: http://jsfiddle.net/juvian/aapdjbpt/