Related
I have chart configured like in working jsfiddle.
I have configured labels(basing on google doc documentation: https://developers.google.com/chart/interactive/docs/gallery/barchart#labeling-bars)
But they aren't visible. When I change chart type to google.visualization.BarChart, then labels appear but bars structure is destroyed. How to add labels to my configuration?
Replicated:
https://jsfiddle.net/41fmq37j/
JS:
google.charts.load('current', {'packages':['corechart', 'bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[{label: 'Year', id: 'year', type: 'number'},
{label: 'Sales', id: 'Sales', type: 'number'},
{label: 'Expenses', id: 'Expenses', type: 'number'},
{ role: 'annotation' }],
[2014, 10, 400 ,'label1'],
[2014, 800, 100 ,'label2'],
[2015, 200, 460 ,'label3'],
[2015, 110, 660 ,'label4'],
[2016, 100, 300 ,'label5'],
[2016, 600, 120 ,'label6'],
[2017, 360, 540 ,'label7'],
[2017, 300, 500 ,'label8']
]);
var options = {
chart: {
title: 'Sales and Expenses',
subtitle: 'Some descr',
},
bars: 'horizontal',
height: 400,
isStacked: true,
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
HTML:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT:
It is possible to configure yAxis like below? Because current format can be confusing.
I would like to create more, a little different graphs, for example which will group bars by string. So another question is: how we can archive grouping yAxis by string? Maybe we should create any comparator?
material charts do not support columns roles, such as 'annotation',
along with several other options
and, it's not possible to have multiple stacks per label in classic charts
as such, we can use a material chart,
and add our own annotations manually,
on the chart's 'ready' event
see following working snippet...
google.charts.load('current', {
packages:['bar']
}).then(function () {
var data = google.visualization.arrayToDataTable([
[
{label: 'Year', id: 'year', type: 'number'},
{label: 'Sales', id: 'Sales', type: 'number'},
{label: 'Expenses', id: 'Expenses', type: 'number'},
{role: 'annotation', type: 'string'}
],
[2014, 10, 400, 'label1'],
[2014, 800, 100, 'label2'],
[2015, 200, 460, 'label3'],
[2015, 110, 660, 'label4'],
[2016, 100, 300, 'label5'],
[2016, 600, 120, 'label6'],
[2017, 360, 540, 'label7'],
[2017, 300, 500, 'label8']
]);
var options = {
chart: {
title: 'Sales and Expenses',
subtitle: 'Some descr',
},
bars: 'horizontal',
height: 400,
isStacked: true,
vAxis: {
format: '0'
}
};
var container = document.getElementById('chart_div');
var chart = new google.charts.Bar(container);
// add annotations
google.visualization.events.addListener(chart, 'ready', function () {
var annotation;
var bars;
var copyLabel;
var coordsBar;
var coordsLabel;
var labels;
var svg;
// get svg
svg = container.getElementsByTagName('svg')[0];
// find label to clone
labels = svg.getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label) {
if (label.textContent === data.getValue(0, 0).toString()) {
copyLabel = label;
}
});
// find top bars, add labels
bars = svg.getElementsByTagName('path');
Array.prototype.forEach.call(bars, function(bar, index) {
coordsBar = bar.getBBox();
annotation = copyLabel.parentNode.insertBefore(copyLabel.cloneNode(true), copyLabel);
coordsLabel = annotation.getBBox();
annotation.textContent = data.getValue(index, 3);
annotation.setAttribute('fill', '#000000');
annotation.setAttribute('x', coordsBar.x + coordsBar.width - 16);
annotation.setAttribute('y', coordsBar.y + coordsBar.height - (coordsLabel.height / 2));
annotation.style.zIndex = -1;
});
});
chart.draw(data, google.charts.Bar.convertOptions(options));
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
the annotation script finds the first y-axis label,
and uses it as a clone for the annotations.
if the values for the y-axis change,
then the script to find the label needs to change.
updated here...
// find label to clone
labels = svg.getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label) {
// find first y-axis label
if (label.textContent === formatDate.formatValue(data.getValue(0, 0))) {
annotation = label;
}
});
see following working snippet...
google.charts.load('current', {
packages:['bar']
}).then(function () {
var data = google.visualization.arrayToDataTable([
[
{label: 'Date', id: 'string', type:'date'},
{label: 'Sales', id: 'Sales', type: 'number'},
{label: 'Expenses', id: 'Expenses', type: 'number'},
{role: 'annotation', type: 'string'}
],
[new Date('2011-12-20'), 10, 400, 'User1'],
[new Date('2011-12-20'), 800, 100, 'User2'],
[new Date('2011-12-21'), 200, 460, 'User3'],
[new Date('2011-12-21'), 200, 460, 'User3'],
]);
var dateFormat = 'YYYY/MM/dd';
var options = {
chart: {
title: 'Sales and Expenses',
subtitle: 'Some descr',
},
bars: 'horizontal',
height: 400,
isStacked: true,
vAxis: {
format: dateFormat,
}
};
var container = document.getElementById('chart_div');
var chart = new google.charts.Bar(container);
var formatDate = new google.visualization.DateFormat({
pattern: dateFormat
});
// add annotations
google.visualization.events.addListener(chart, 'ready', function () {
var annotation;
var bars;
var copyLabel;
var coordsBar;
var coordsLabel;
var labels;
var svg;
// get svg
svg = container.getElementsByTagName('svg')[0];
// find label to clone
labels = svg.getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label) {
// find first y-axis label
if (label.textContent === formatDate.formatValue(data.getValue(0, 0))) {
copyLabel = label;
}
});
// find top bars, add labels
bars = svg.getElementsByTagName('path');
Array.prototype.forEach.call(bars, function(bar, index) {
coordsBar = bar.getBBox();
annotation = copyLabel.parentNode.insertBefore(copyLabel.cloneNode(true), copyLabel);
coordsLabel = annotation.getBBox();
annotation.textContent = data.getValue(index, 3);
annotation.setAttribute('fill', '#ffffff');
annotation.setAttribute('text-anchor', 'start');
annotation.setAttribute('x', coordsBar.x + coordsBar.width);
annotation.setAttribute('y', coordsBar.y + (coordsBar.height / 2) + (coordsLabel.height / 2));
annotation.style.zIndex = -1;
});
});
chart.draw(data, google.charts.Bar.convertOptions(options));
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
how can I highlight a single grid line? I would like to set an optical temperature limit at 35 ° C.
Thanks! I have now added it to my code, but it does not work .... do you see my mistake? Or did I not understand something in your explanation?
Here is the edited version :
//Google Chart
google.charts.load('current', {
callback: function drawChart(peanut) {
const div = document.createElement('div');
div.id = peanut.color + peanut.mac.split(':').join('');
$('#charts').appendChild(div);
peanut.data = new google.visualization.DataTable();
peanut.data.addColumn('datetime', 'Time');
peanut.data.addColumn('number', '🥜 ' + peanut.label);
for (var i = 0, len = localStorage.length; i < len; i++) {
let dateTime = new Date(parseInt(localStorage.key(i)));
let item = JSON.parse(localStorage.getItem(localStorage.key(i)));
if (item.peanutMac === peanut.mac) {
if (item.temperatureCelsius) {
let temperature = parseFloat(item.temperatureCelsius);
peanut.data.addRows([ [dateTime, temperature] ]);
} else if (item.alert) {
let data = parseInt(item.alert);
peanut.data.addRows([ [dateTime, data] ]);
}
}
}
if (peanut.type == 'thermo') {
peanut.chart = new google.visualization.LineChart($('#' + div.id));
peanut.chartOptions = {
interpolateNulls: true,
fontName: 'Roboto',
curveType: 'function',
colors: [peanut.rgbColor],
width: document.body.clientWidth,
height: (window.innerHeight - 224) / 2,
legend: 'none',
lineWidth: 3,
vAxis: {
format: '#.## °C',
ticks: [15.00, 20.00, 25.00, 30.00, 35.00, 40.00]
},
hAxis: {
gridlines: {
color: '#fff'
}
}
};
peanut.viewColumns = [];
$.each(new Array(data.getNumberOfColumns()), function (colIndex) {
peanut.viewColumns.push(colIndex);
});
peanut.viewColumns.push({
calc: function () {
return 35;
},
label: 'optical temperature limit',
type: 'number'
});
}
peanut.view = new google.visualiation.DataView(data);
peanut.view.setColumns(viewColumns);
if (peanut.data.getNumberOfRows()) {
peanut.chart.draw(peanut.view, peanut.chartOptions);
}
}
packages:['corechart', 'table']
});
add another series with the value set to 35 for all rows
here, a data view is used to add a calculated column for the optical temperature limit
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn('number', 'y0');
data.addColumn('number', 'y1');
data.addColumn('number', 'y2');
data.addRows([
[1, 32.8, 20.8, 21.8],
[2, 30.9, 29.5, 32.4],
[3, 25.4, 27, 25.7],
[4, 21.7, 28.8, 20.5],
[5, 21.9, 27.6, 20.4]
]);
var options = {
interpolateNulls: true,
fontName: 'Roboto',
curveType: 'function',
legend: 'none',
lineWidth: 3,
vAxis: {
format: '#.## °C',
ticks: [20.00, 25.00, 30.00, 35.00, 40.00]
},
hAxis: {
gridlines: {
color: '#fff'
}
}
};
var viewColumns = [];
$.each(new Array(data.getNumberOfColumns()), function (colIndex) {
viewColumns.push(colIndex);
});
viewColumns.push({
calc: function () {
return 35;
},
label: 'optical temperature limit',
type: 'number'
});
var view = new google.visualization.DataView(data);
view.setColumns(viewColumns);
var chart = new google.visualization.LineChart($('#chart').get(0));
chart.draw(view, options);
},
packages:['corechart', 'table']
});
<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>
Its not the best and safest way but I didnt find something on the google documentation:
You could use Jquery for it Ive tried it on the example from google docs and it works click
var line = $("svg g line")[4]
$(line).attr('stroke','red');
A simple way is to set the vAxis baseline to the value you want, say 35, and change the baselineColor. There is no option to change the width of this line, however, so if you need that, you should follow the suggestion above to add a series just to draw this line, and set its lineWidth.
i'm trying to use Google Chart API for building an Waterfall chart. I noticed that Candlestick/Waterfall charts are not supporting the annotations.
See this jsfiddle sample
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'MinimumLevel');
data.addColumn('number', 'MinimumLevel1');
data.addColumn('number', 'MaximumLevel');
data.addColumn('number', 'MaximumLevel1');
data.addColumn({type: 'number', role: 'tooltip'});
data.addColumn({type: 'string', role: 'style'});
data.addColumn({type: 'number', role: 'annotation'});
data.addRow(['Category 1', 0 , 0, 5, 5, 5,'gray',5]);
data.addRow(['Category 2', 5 , 5, 10, 10, 10,'red',10]);
data.addRow(['Category 3', 10 , 10, 15, 15, 15,'blue',15]);
data.addRow(['Category 4', 15 , 15, 10, 10, 10,'yellow',10]);
data.addRow(['Category 5', 10 , 10, 5, 5, 5,'gray',5]);
var options = {
legend: 'none',
bar: { groupWidth: '60%' } // Remove space between bars.
};
var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I would like to put the value of the 5th column at the top of every candlestick.
It should look like this :
Is there a way to do this?
Thanks
I add annotations to candlestick charts by adding annotations to a hidden scatter plot. You can set exactly where you want the annotations to sit by changing the plot.
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Low');
data.addColumn('number', 'Open');
data.addColumn('number', 'Close');
data.addColumn('number', 'High');
data.addColumn('number'); //scatter plot for annotations
data.addColumn({ type: 'string', role: 'annotation' }); // annotation role col.
data.addColumn({ type: 'string', role: 'annotationText' }); // annotationText col.
var high, low, open, close = 160;
for (var i = 0; i < 10; i++) {
open = close;
close += ~~(Math.random() * 10) * Math.pow(-1, ~~(Math.random() * 2));
high = Math.max(open, close) + ~~(Math.random() * 10);
low = Math.min(open, close) - ~~(Math.random() * 10);
annotation = '$' + close;
annotation_text = 'Close price: $' + close;
data.addRow([new Date(2014, 0, i + 1), low, open, close, high, high, annotation, annotation_text]);
}
var view = new google.visualization.DataView(data);
var chart = new google.visualization.ComboChart(document.querySelector('#chart_div'));
chart.draw(view, {
height: 400,
width: 600,
explorer: {},
chartArea: {
left: '7%',
width: '70%'
},
series: {
0: {
color: 'black',
type: 'candlesticks',
},
1: {
type: 'scatter',
pointSize: 0,
targetAxisIndex: 0,
},
},
candlestick: {
color: '#a52714',
fallingColor: { strokeWidth: 0, fill: '#a52714' }, // red
risingColor: { strokeWidth: 0, fill: '#0f9d58' } // green
},
});
}
<script type="text/javascript"src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
just so happens, i ran into the same problem this week
so I added my own annotations, during the 'animationfinish' event
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var dataChart = new google.visualization.DataTable({"cols":[{"label":"Category","type":"string"},{"label":"Bottom 1","type":"number"},{"label":"Bottom 2","type":"number"},{"label":"Top 1","type":"number"},{"label":"Top 2","type":"number"},{"role":"style","type":"string","p":{"role":"style"}}],"rows":[{"c":[{"v":"Budget"},{"v":0},{"v":0},{"v":22707893.613},{"v":22707893.613},{"v":"#007fff"}]},{"c":[{"v":"Contract Labor"},{"v":22707893.613},{"v":22707893.613},{"v":22534350.429},{"v":22534350.429},{"v":"#1e8449"}]},{"c":[{"v":"Contract Non Labor"},{"v":22534350.429},{"v":22534350.429},{"v":22930956.493},{"v":22930956.493},{"v":"#922b21"}]},{"c":[{"v":"Materials and Equipment"},{"v":22930956.493},{"v":22930956.493},{"v":22800059.612},{"v":22800059.612},{"v":"#1e8449"}]},{"c":[{"v":"Other"},{"v":22800059.612},{"v":22800059.612},{"v":21993391.103},{"v":21993391.103},{"v":"#1e8449"}]},{"c":[{"v":"Labor"},{"v":21993391.103},{"v":21993391.103},{"v":21546003.177999996},{"v":21546003.177999996},{"v":"#1e8449"}]},{"c":[{"v":"Travel"},{"v":21546003.177999996},{"v":21546003.177999996},{"v":21533258.930999994},{"v":21533258.930999994},{"v":"#1e8449"}]},{"c":[{"v":"Training"},{"v":21533258.930999994},{"v":21533258.930999994},{"v":21550964.529999994},{"v":21550964.529999994},{"v":"#922b21"}]},{"c":[{"v":"Actual"},{"v":0},{"v":0},{"v":21550964.52999999},{"v":21550964.52999999},{"v":"#007fff"}]}]});
var waterFallChart = new google.visualization.ChartWrapper({
chartType: 'CandlestickChart',
containerId: 'chart_div',
dataTable: dataChart,
options: {
animation: {
duration: 1500,
easing: 'inAndOut',
startup: true
},
backgroundColor: 'transparent',
bar: {
groupWidth: '85%'
},
chartArea: {
backgroundColor: 'transparent',
height: 210,
left: 60,
top: 24,
width: '100%'
},
hAxis: {
slantedText: false,
textStyle: {
color: '#616161',
fontSize: 9
}
},
height: 272,
legend: 'none',
tooltip: {
isHtml: true,
trigger: 'both'
},
vAxis: {
format: 'short',
gridlines: {
count: -1
},
textStyle: {
color: '#616161'
},
viewWindow: {
max: 24000000,
min: 16000000
}
},
width: '100%'
}
});
google.visualization.events.addOneTimeListener(waterFallChart, 'ready', function () {
google.visualization.events.addListener(waterFallChart.getChart(), 'animationfinish', function () {
var annotation;
var chartLayout;
var container;
var numberFormatShort;
var positionY;
var positionX;
var rowBalance;
var rowBottom;
var rowFormattedValue;
var rowIndex;
var rowTop;
var rowValue;
var rowWidth;
container = document.getElementById(waterFallChart.getContainerId());
chartLayout = waterFallChart.getChart().getChartLayoutInterface();
numberFormatShort = new google.visualization.NumberFormat({
pattern: 'short'
});
rowIndex = 0;
Array.prototype.forEach.call(container.getElementsByTagName('rect'), function(rect) {
switch (rect.getAttribute('fill')) {
// use colors to identify bars
case '#922b21':
case '#1e8449':
case '#007fff':
rowWidth = parseFloat(rect.getAttribute('width'));
if (rowWidth > 2) {
rowBottom = waterFallChart.getDataTable().getValue(rowIndex, 1);
rowTop = waterFallChart.getDataTable().getValue(rowIndex, 3);
rowValue = rowTop - rowBottom;
rowBalance = Math.max(rowBottom, rowTop);
positionY = chartLayout.getYLocation(rowBalance) - 6;
positionX = parseFloat(rect.getAttribute('x'));
rowFormattedValue = numberFormatShort.formatValue(rowValue);
if (rowValue < 0) {
rowFormattedValue = rowFormattedValue.replace('-', '');
rowFormattedValue = '(' + rowFormattedValue + ')';
}
annotation = container.getElementsByTagName('svg')[0].appendChild(container.getElementsByTagName('text')[0].cloneNode(true));
$(annotation).text(rowFormattedValue);
annotation.setAttribute('x', (positionX + (rowWidth / 2)));
annotation.setAttribute('y', positionY);
annotation.setAttribute('font-weight', 'bold');
rowIndex++;
}
break;
}
});
});
});
$(window).resize(function() {
waterFallChart.draw();
});
waterFallChart.draw();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
See the example code:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Mac');
data.addColumn('number', 'Score');
data.addColumn({ type: 'string', role: 'style' });
data.addRows([
['Mac model 12', 200, 'color: #8bba30; opacity: 0.75;'],
['Another Mac Model', 110, 'color: #ffcc33; opacity: 0.75;'],
]);
var options = {
title: '',
width: 500,
height: data.getNumberOfRows() * 40 + 100,
hAxis: {
minValue: 0,
maxValue: 255,
ticks: [0, 75, 150, 255],
textPosition: 'out',
side: 'top'
},
series: {
0: { axis: 'Mac' },
1: { axis: 'Score' }
},
chartArea: {
top: 0,
bottom: 50,
right: 50,
left: 150
},
legend: { position: 'none' },
fontSize: 12,
bar: {groupWidth: '75%'},
};
var chart = new google.visualization.BarChart(document.getElementById('apple_div'));
chart.draw(data, options);
}
This is the output:
See, there are different colors for different bars. But I want different color and/or background-color for different legends on left side.
Can someone help me with this please?
I found following answer, Is it possible to show each legend in different color in google pie chart.
But it suggests on breaking down the chart(i.e. to draw separate charts for each rows), which is not desirable as there are large numbers of rows.
Not sure what you mean by breaking the chart, but...
You can modify the chart svg, once the 'ready' event fires.
This example changes the color of the legend text to match the bar color.
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var colors = ['#8bba30', '#ffcc33'];
var data = new google.visualization.DataTable();
data.addColumn('string', 'Mac');
data.addColumn('number', 'Score');
data.addColumn({ type: 'string', role: 'style' });
data.addRows([
['Mac model 12', 200, 'color: ' + colors[0] + '; opacity: 0.75;'],
['Another Mac Model', 110, 'color: ' + colors[1] + '; opacity: 0.75;'],
]);
var options = {
title: '',
width: 500,
height: data.getNumberOfRows() * 40 + 100,
hAxis: {
minValue: 0,
maxValue: 255,
ticks: [0, 75, 150, 255],
textPosition: 'out',
side: 'top'
},
series: {
0: { axis: 'Mac' },
1: { axis: 'Score' }
},
chartArea: {
top: 0,
bottom: 50,
right: 50,
left: 150
},
legend: { position: 'none' },
fontSize: 12,
bar: {groupWidth: '75%'},
};
var chartContainer = document.getElementById('apple_div');
var chart = new google.visualization.BarChart(chartContainer);
google.visualization.events.addListener(chart, 'ready', function () {
var labels = chartContainer.getElementsByTagName('text');
var colorIndex = 0;
for (var i = 0; i < labels.length; i++) {
if (labels[i].getAttribute('text-anchor') === 'end') {
labels[i].setAttribute('fill', colors[colorIndex]);
colorIndex++;
}
}
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="apple_div"></div>
As for background color, SVG elements do not have background
so you would have to draw your own rect for that...
I'm currently working on a chart using google chart api, but i struggle at making a twice positive horizontal scale.
Like : 50 25 0 25 50 with a stacked chart bar centered on the '0' in the scale.
I kind of got it centered using a "dummy" invisible bar to push everything, but i can't find a way to get the horizontal axis label customized without editing the windowsview.
here's my actual code :
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawAnnotations);
function findMax(arr) {
var max = 0;
for (var n in arr) {
if (n > 0) {
var cMax = arr[n][2];
if (cMax > max)
max = cMax
}
}
return (max);
}
function findLine(arr) {
var max = 0;
for (var n in arr) {
if (n > 0) {
var cMax = arr[n][2] + arr[n][3] + arr[n][4];
if (cMax > max)
max = cMax
}
}
return (max / 2);
}
function space(arr, maxL) {
var max = findMax(arr);
for (var n in arr) {
if (n > 0) {
arr[n][1] = max - arr[n][2] + (maxL);
}
}
}
function drawAnnotations() {
var raw_data = [];
raw_data.push( ['Compétence', 'invisible', 'Expert', 'Certifié', 'Non certifié'] );
raw_data.push( ['Java', 0, 24, 31, 12] );
raw_data.push( ['PHP', 0, 17, 22, 10] );
raw_data.push( ['JavaScript', 0, 6, 10, 22] );
raw_data.push( ['Cpp', 0, 0, 0, 50] );
raw_data.push( ['C#', 0, 5, 10, 15] );
var maxL = findLine(raw_data);
space(raw_data, maxL);
var data = google.visualization.arrayToDataTable(raw_data);
var options = {
isStacked: true,
enableInteractivity: false,
width: 600, height: 400,
legend : 'none',
bar: { groupWidth: '85%' },
colors: ['ffffff','gray', 'yellow', 'red'],
hAxis: {
title: '',
baselineColor: '#fff',
gridlineColor: '#fff'
},
vAxis: {
title: '',
baselineColor: '#fff',
gridlineColor: '#fff'
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
JSfiddle Link
Currently i got what i want exept for the horizontal scale which is not set as i wish it to be.
(I tried to use multiple axes but it has proven to be unseccessfull).
edit: I add a link to an image of what kind of chart (scale) i'm looking to do.
UPDATE
I kinda got it working now :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawAnnotations);
function drawAnnotations() {
var raw_data = [];
raw_data.push( ['Compétence', 'Expert', 'Certifié', 'Non certifié'] );
raw_data.push( ['Java', -24, 45, 12] );
raw_data.push( ['PHP', -17, 22, 10] );
raw_data.push( ['JavaScript', -6, 10, 22] );
raw_data.push( ['Cpp', -0, 0, 50] );
raw_data.push( ['C#', -5, 10, 15] );
var data = google.visualization.arrayToDataTable(raw_data);
var options = {
isStacked: true,
width: $(window).width() * 0.8, height: 400,
legend : 'none',
bar: { groupWidth: '85%' },
colors: ['gray', 'yellow', 'red'],
interpolateNulls: true,
hAxis: {
title: 'Number',
gridlines: {
color: 'transparent'
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
$(window).load(function() {
$('text').each(function(i, el) {
if ($(this).text()[0] == '-')
$(this).text($(this).text().substr(1));
});
});
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
I had to change the google lib i was using :
previously was :
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
and now i'm using :
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
I'm not sure why it change something but without this change $(window).load was unable to reach "text" and i wasn't able to edit it.
Now i'm just converting a part of my chart to negative (the one i wanted on the left) and change the "negative" values from the scale using jquery.
There's just one thing left , the tooltip still show the negative value when you point on the "gray" area of the chart.
I still hope it may help someone else who struggle with this particular problem.
In fact, instead of modifying axis text via jQuery you could customize it via ticks feature as shown below:
hAxis: {
ticks: [{ v: -25, f: '25' }, 0, 25, 50, 75]
}
Regrading customizing tooltip label, you could consider the following solution to display non-negative value:
1) Attach onmouseover event to Google Chart:
google.visualization.events.addListener(chart, 'onmouseover', function (e) {
setTooltipContent(data, e);
});
2) Override tooltip negative value:
function setTooltipContent(data, e) {
if (e.row != null && e.column == 1) {
var val = Math.abs(data.getValue(e.row, 1));
var tooltipTextLabel = $(".google-visualization-tooltip-item-list li:eq(1) span:eq(1)");
tooltipTextLabel.text(val.toString());
}
}
Complete example
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawAnnotations);
function drawAnnotations() {
var raw_data = [];
raw_data.push(['Compétence', 'Expert', 'Certifié', 'Non certifié']);
raw_data.push(['Java', -24, 45, 12]);
raw_data.push(['PHP', -17, 22, 10]);
raw_data.push(['JavaScript', -6, 10, 22]);
raw_data.push(['Cpp', -0, 0, 50]);
raw_data.push(['C#', -5, 10, 15]);
var data = google.visualization.arrayToDataTable(raw_data);
var options = {
isStacked: true,
width: $(window).width() * 0.8, height: 400,
legend: 'none',
bar: { groupWidth: '85%' },
colors: ['gray', 'yellow', 'red'],
interpolateNulls: true,
tooltip: {isHtml: true},
hAxis: {
title: 'Number',
gridlines: {
color: 'transparent'
},
ticks: [{ v: -25, f: '25' }, 0, 25, 50, 75]
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'onmouseover', function (e) {
setTooltipContent(data, e);
});
}
function setTooltipContent(data, e) {
if (e.row != null && e.column == 1) {
var val = Math.abs(data.getValue(e.row, 1));
var tooltipTextLabel = $(".google-visualization-tooltip-item-list li:eq(1) span:eq(1)");
tooltipTextLabel.text(val.toString());
}
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
JSFiddle