Google Charts - Apply margin on y-axis values - charts

What I'd like to do, is to increase the margin between the y-axis values and the corresponding bar within the chart.
So if I have a bar in the chart which has a value of "Python" on the Y- axis, I want to increase the space between the string "Python" and the visual bar.
Now:
Python__========================================================
My goal:
Python___________=========================================================
___ represents the space between y-axis label and visual bar
I tried to use chartArea{right:200} and textPosition:out in the options section of the chart.
var options = {
chartArea:{right: 200},
'vAxis': {
title:'',
textStyle : {
fontSize: 25
},
textPosition: 'out'
},
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Coding-Skills', 'Skill-Level'],
['C', {v: 0.3, f:'low'}],
['Python', {v: 1, f:'medium'}],
['Javascript', {v: 1.5, f:'medium'}],
['HTML/CSS', {v: 1.5, f:'medium'} ]
]);
var options = {
chartArea: {
left: 1400
},
'hAxis': {
gridlines:{
count: 0},
textStyle : {
fontSize: 25
}
},
'vAxis': {
title:'',
textStyle : {
fontSize: 25
}
},
chart: {
},
bars: 'horizontal',
axes: {
x: {
0: { side: 'bottom', label: 'Years of experience'} ,
textStyle : {
fontSize: 35
}
}
}
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
Applying margin-right

no options for label margins,
but you can move them manually on the chart's 'ready' event
find the labels and change the 'x' attribute
see following working snippet,
here, the chartArea option is used to ensure there is enough room...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Language', 'Skill-Level'],
['C', 20],
['Python', 35],
['Javascript', 50]
]);
var container = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var labels = container.getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label) {
// move axis labels
if (label.getAttribute('text-anchor') === 'end') {
var xCoord = parseFloat(label.getAttribute('x'));
label.setAttribute('x', xCoord - 20);
}
});
});
var options = {
chartArea: {
left: 100,
right: 200
},
colors: ['#aaaaaa'],
hAxis: {
baselineColor: 'transparent',
gridlines: {
count: 0
},
textStyle: {
color: '#aaaaaa'
}
},
height: 400,
legend: {
textStyle: {
color: '#aaaaaa'
}
},
vAxis: {
textStyle: {
color: '#aaaaaa'
}
}
};
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Quick addition to existing answer:
$('.transactionValuationChart text').each(function(){
if( $(this).attr('text-anchor') == 'middle' ){
$(this).attr('y', parseFloat($(this).attr('y')) + 20 );
}else{
$(this).attr('x', parseFloat($(this).attr('x')) - 20 );
console.log("left");
}
});
This is a jQuery example which adds 20px of spacing to both x & y axis

Related

Google Chart - Bar Series Title Different Color

I have a chart which has 4 series (Fiddle link below). Currently, it has Title1, Title2, Title3, and Title4. I want to change the different color for each title text name (Not the bar); for example, Title1 is red, Title2 is blue, Title3 is green, and Title4 is black. Is there a way to change all these titles with different colors?
https://jsfiddle.net/milacay/e4fe4hsz/21/
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test Google Chart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {callback: drawChart, packages: ['corechart']});
function drawChart() {
var array = [
["", "Today", "Goal"],
["Title1", 4553, 4151],
["Title2", 5560, 6150],
["Title3", 850, 920],
["Title4", 10505, 12320]
];
var data = new google.visualization.arrayToDataTable(array);
var formatTooltip = new google.visualization.NumberFormat({
pattern : '#,##0'
});
formatTooltip.format(data, 1);
formatTooltip.format(data, 2);
var formatShort = new google.visualization.NumberFormat({
pattern : 'short'
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc : function (dt, row) {
return formatShort.formatValue(dt.getValue(row, 1));
},
type : "string",
role : "annotation"
},
2, {
calc : function (dt, row) {
return formatShort.formatValue(dt.getValue(row, 2));
},
type : "string",
role : "annotation"
},
]);
var options = {
chart: {
title: ' ',
animation: {
duration: 2000,
easing: "out",
startup: true,
}
},
chartArea: {right:0
, width: "80%"
, height: "80%"
},
bar: {
groupWidth: 55 // Set the width for each bar
},
legend: {position:'top'},
hAxis: {
format: 'short',
//title: 'Month',
textStyle : {
bold: true,
fontSize: 10 // fontsize for the vAxis label.
//color: 'darkblue',
},
},
vAxis: {
format: 'short',
title: 'Progress To-Date',
gridlines: { count: 8 }
},
width:320,
height:300,
bars: 'vertical',
colors: ["lightblue", "lightgray"]
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
if you want to change the color of the axis labels,
change those manually when the chart's 'ready' event fires,
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var array = [
["", "Today", "Goal"],
["Title1", 4553, 4151],
["Title2", 5560, 6150],
["Title3", 850, 920],
["Title4", 10505, 12320]
];
var data = new google.visualization.arrayToDataTable(array);
var formatTooltip = new google.visualization.NumberFormat({
pattern : '#,##0'
});
formatTooltip.format(data, 1);
formatTooltip.format(data, 2);
var formatShort = new google.visualization.NumberFormat({
pattern : 'short'
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc : function (dt, row) {
return formatShort.formatValue(dt.getValue(row, 1));
},
type : "string",
role : "annotation"
},
2, {
calc : function (dt, row) {
return formatShort.formatValue(dt.getValue(row, 2));
},
type : "string",
role : "annotation"
},
]);
var options = {
chart: {
title: ' ',
animation: {
duration: 2000,
easing: "out",
startup: true,
}
},
chartArea: {right:0
, width: "80%"
, height: "80%"
},
bar: {
groupWidth: 55 // Set the width for each bar
},
legend: {position:'top'},
hAxis: {
format: 'short',
//title: 'Month',
textStyle : {
bold: true,
fontSize: 10 // fontsize for the vAxis label.
//color: 'darkblue',
},
},
vAxis: {
format: 'short',
title: 'Progress To-Date',
gridlines: { count: 8 }
},
width:320,
height:300,
bars: 'vertical',
colors: ["lightblue", "lightgray"]
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var colorIndex = 0;
var colorPallette = ['red', 'blue', 'green', 'black'];
Array.prototype.forEach.call(container.getElementsByTagName('text'), function (label) {
if ((label.getAttribute('text-anchor') === 'middle') && (label.getAttribute('fill') !== '#404040')) {
label.setAttribute('fill', colorPallette[colorIndex]);
colorIndex++;
}
});
});
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: the label color (#404040) is used to differentiate the x-axis labels from the annotation labels...

Google Bar chart bars & axis do not correlate to data

https://i.imgur.com/qKcSRjS.png
The values of the bars, from top to bottom, are 66, 77, 91, 0
As you can see, the labels on the X axis are not to scale and seem to simply indicate the value of each bar, and the bars are also not scaled to their value they seem to simply stack in a staircase fashion. The bottom bar should be 'empty' as it is 0.
The data is dynamically generated but here is the resulting code:
function drawRightY() {
var data = google.visualization.arrayToDataTable([ ['Date', 'Received'], ['1/15/2018', '66'],['1/22/2018', '77'],['1/29/2018', '91'],['2/5/2018', '0'] ]);
var materialOptions = {
chart: {
hAxis: {
title: 'Date',
minValue: 0,
scaleType: 'log'
},
vAxis: {
title: 'Received'
},
bars: 'horizontal',
legend: {
position: 'none'
},
axes: {
y: {
0: { side: 'left' }
}
}
};
the values in the data should be numbers, not strings (remove single quotes)
['1/15/2018', '66'] // <-- string
['1/15/2018', 66] // <-- number
see following working snippet...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([ ['Date', 'Received'], ['1/15/2018', 66],['1/22/2018', 77],['1/29/2018', 91],['2/5/2018', 0] ]);
var materialOptions = {
hAxis: {
title: 'Date',
minValue: 0,
scaleType: 'log'
},
vAxis: {
title: 'Received'
},
bars: 'horizontal',
legend: {
position: 'none'
},
axes: {
y: {
0: { side: 'left' }
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart'));
chart.draw(data);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

Google Charts focusTarget: 'category' not working

Google Charts focusTarget: 'category' works when I draw the chart in one way but not in the other one.
In the example below, the BAR I has a broken tooltip (not triggering the way intended) and it's working perfectly fine with the BAR II
google.charts.load('current', {
'packages': ['corechart', 'bar']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// _____ BAR I ______
var data = google.visualization.arrayToDataTable([
['Form', 'Visitors', 'Starters', 'Conversions'],
['Form 1', 1000, 650, 490],
['Form 2', 485, 460, 350],
['Form 3', 335, 250, 105]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
focusTarget: 'category',
},
focusTarget: 'category',
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
// ______ BAR II ______
var data = google.visualization.arrayToDataTable([
['Form', 'Visitors', 'Starters', 'Conversions'],
['Form 1', 1000, 650, 490],
['Form 2', 485, 460, 350],
['Form 3', 335, 250, 105]
]);
var options = {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
// This line makes the entire category's tooltip active.
focusTarget: 'category',
// Use an HTML tooltip.
tooltip: {
isHtml: true
}
};
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('columnchart_material_2')).draw(data, options);
}
Please also take a look at this JSFiddle of the problem.
Besides different tooltip behavior, the charts also look rather different, what is the cause?
one is considered a Classic chart, the other Material
Classic --> google.visualization.ColumnChart -- requires package: 'corechart'
Material --> google.charts.Bar -- requires package: 'bar'
Material charts are newer, but also do not support several options...
see --> Tracking Issue for Material Chart Feature Parity
which includes...
focusTarget
there is an option for Classic charts, to style them similar to Material
theme: 'material'
Here is the codepen link for using google charts
google.charts.load('visualization', '1', {
'packages': ['corechart'],
"callback": drawChart
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Year", "Relevance", {
role: "style"
}],
["Forward ref..", 108, "#25C16F"],
["Case ref..", 20, "#25C16F"],
["Approved", 30, "#25C16F"],
["Disapproved", 50, "#25C16F"],
["Distinguish", 25.67, "#25C16F"],
["Followed", 28.9, "color: #25C16F"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
title: "Case Relevance",
width: 350,
height: 300,
bar: {
groupWidth: "50%",
},
hAxis: {
title: 'Relevance',
viewWindow: {
min: 0,
max: 120
},
ticks: [0, 30, 60, 90, 120] // display labels every 25
},
legend: {
position: "none"
},
};
var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
chart.draw(vieenter code herew, options);
google.visualization.events.addListener(chart, 'select', function() {
var row = chart.getSelection()[0].row;
if (row == 0) {
$("#right_panel h2").children(".small-font").html("Forward Reference in");
} else if (row == 1) {
$("#right_panel h2").children(".small-font").html("Case Reference");
} else if (row == 2) {
$("#right_panel h2").children(".small-font").html("Approved");
} else if (row == 3) {
$("#right_panel h2").children(".small-font").html("Disapproved");
} else if (row == 4) {
$("#right_panel h2").children(".small-font").html("Distinguish");
} else if (row == 5) {
$("#right_panel h2").children(".small-font").html("Followed");
}
});
}
});
https://codepen.io/shray04/pen/Poogmjq?editors=1000

Material design google charts change color column

When using Google charts, usually you can change the colors of individual columns by using the "role: style" function, but when I attempt it with the new material design charts I only get blue columns.
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['', '', { role: 'style' } ],
["Strongly disagree", 0, 'color: black'],
["Disagree", 0, 'color: #000000'],
["Neutral", 6, 'color: #212121'],
["Agree", 45, 'color: #212121'],
['Stongly agree', 98, 'color: black']
]);
var options = {
title: 'Instructor presented the subject matter clearly',
width: 900,
legend: { position: 'none' },
chart: { subtitle: 'General physics 221 CSUSB winter 2017' },
axes: {
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
// Convert the Classic options to Material options.
chart.draw(data, google.charts.Bar.convertOptions(options));
};
You can try with netx code:
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawColColors);
function drawColColors() {
var data = new google.visualization.arrayToDataTable([
['', '', { role: 'style' } ],
["Strongly disagree", 12, 'brown'],
["Disagree", 30, 'gray'],
["Neutral", 26, 'blue'],
["Agree", 45, 'color: #F05921'],
['Stongly agree', 58, 'black']
]);
var options = {
title: 'Instructor presented the subject matter clearly',
width: 900,
legend: { position: 'none' },
chart: { subtitle: 'General physics 221 CSUSB winter 2017' },
axes: {
},
bar: { groupWidth: "90%" }
};
//var chart = new google.charts.Bar(document.getElementById('chart_div'));
// Convert the Classic options to Material options.
//chart.draw(data, google.charts.Bar.convertOptions(options));
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
};
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Different colors for annotations in google charts

I have two types of annotations, one has links and other doesn't. I want to color them both in different colors. Is it possible?
type 1 is -
{
v: 'sample',
Link: 'some link
}
type 2 is -
{
v: 'sample',
}
I want to color type1 in some color and type2 in other, is it possible ?
you can style the annotations for the overall chart,
or for each series individually
see following working snippet,
the fontSize is set to 10 for all annotations
then the colors are changed for the individual series
google.charts.load('current', {
callback: drawStacked,
packages: ['corechart']
});
function drawStacked() {
var data = new google.visualization.arrayToDataTable([
['Month', 'A', {role: 'annotation'}, 'B', {role: 'annotation'}],
['Aug', 3754, '3,754', 2089, '2,089'],
['Sept', 900, '900', 200, '200'],
['Oct', 2000, '2,000', 4900, '4,900'],
['Nov', 1700, '1,700', 2200, '2,200'],
['Dec', 2400, '2,400', 2089, '2,089']
]);
var options = {
annotations: {
textStyle: {
fontSize: 10
}
},
series: {
0: {
annotations: {
stem: {
color: 'cyan',
length: 5
},
textStyle: {
color: 'cyan'
}
}
},
1: {
annotations: {
stem: {
color: 'magenta',
length: 10
},
textStyle: {
color: 'magenta'
}
}
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
to have different colors for annotations in a single series,
need to change color manually when the 'ready' event fires
see following working snippet...
google.charts.load('current', {
callback: drawStacked,
packages: ['corechart']
});
function drawStacked() {
var data = new google.visualization.arrayToDataTable([
['Month', 'A', {role: 'annotation'}],
['Aug', 3754, '3,754'],
['Sept', {v: 900, p: {link: 'type A'}}, '900'],
['Oct', {v: 2000, p: {link: 'type B'}}, '2,000'],
['Nov', 1700, '1,700'],
['Dec', 2400, '2,400']
]);
var options = {
annotations: {
textStyle: {
color: '#000000',
fontSize: 10
}
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
Array.prototype.forEach.call(container.getElementsByTagName('text'), function (text, index) {
for (var i = 0; i < data.getNumberOfRows(); i++) {
if ((text.getAttribute('text-anchor') === 'middle') && (text.innerHTML === data.getFormattedValue(i, 1))) {
switch (data.getProperty(i, 1, 'link')) {
case 'type A':
text.setAttribute('fill', 'magenta');
break;
case 'type B':
text.setAttribute('fill', 'cyan');
break;
}
}
}
});
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>