Annotation with symbols inside stacked bar charts using Google Chart API - javascript

I have a stacked bar chart where I need to annotate the bars with $ symbol as the profit and costs are currency.
I am successful in annotating of the bars without currency symbol but I am unable to display with the $ prefixed. Could anyone throw light on this
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {
packages: ["corechart"]
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var bar_chart_data = [
["Material", "Cost", "Profit", { role: 'style' },{ role: 'style' }],
["A", 100, 25, 'color: #F9F528','color: #0ACB53'],
["B", 4.2, 1.764, 'color: #F9F528','color: #0ACB53'],
["C", 110, 46.199999999999996, 'color: #F9F528','color: #0ACB53'],
["D", 7.56, 3.1752, 'color: #F9F528','color: #0ACB53'],
["E", 4.24, 1.7808, 'color: #F9F528','color: #0ACB53'],
["F", 0.8, 0.336, 'color: #F9F528','color: #0ACB53'],
["G", 2, 0.84, 'color: #F9F528','color: #0ACB53'],
["H", 0.8, 0.336, 'color: #F9F528','color: #0ACB53'],
]
var data = google.visualization.arrayToDataTable(bar_chart_data);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}, 3, // <-- include style column
2, {
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
}, 4 // <-- include style column
]);
var options = {
title: "Live individual material cost break-up (%)",
width: 600,
height: 400,
bar: {
groupWidth: "95%"
},
legend: {
position: "none"
},
isStacked: 'percent',
hAxis: {
title: 'Percentage',
textStyle: {
fontSize: 8,
fontName: 'Muli',
bold: false,
},
titleTextStyle: {
fontSize: 12,
fontName: 'Muli',
bold: true,
}
},
vAxis: {
title: 'Material',
textStyle: {
fontSize: 10,
bold: false
},
titleTextStyle: {
fontSize: 12,
bold: true
}
},
};
var chart = new google.visualization.BarChart(document.getElementById("material_bar_chart"));
chart.draw(view, options);
}
</script>
</head>
<body>
<div id="material_bar_chart" style="width: 900px; height: 500px;"></div>
</body>
</html>

use google's NumberFormat class
you can create a pattern, and format each data column.
var formatCurr = new google.visualization.NumberFormat({pattern: '$#,##0'});
formatCurr.format(data, 1);
formatCurr.format(data, 2);
see following working snippet...
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {
packages: ["corechart"]
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var bar_chart_data = [
["Material", "Cost", "Profit", { role: 'style' },{ role: 'style' }],
["A", 100, 25, 'color: #F9F528','color: #0ACB53'],
["B", 4.2, 1.764, 'color: #F9F528','color: #0ACB53'],
["C", 110, 46.199999999999996, 'color: #F9F528','color: #0ACB53'],
["D", 7.56, 3.1752, 'color: #F9F528','color: #0ACB53'],
["E", 4.24, 1.7808, 'color: #F9F528','color: #0ACB53'],
["F", 0.8, 0.336, 'color: #F9F528','color: #0ACB53'],
["G", 2, 0.84, 'color: #F9F528','color: #0ACB53'],
["H", 0.8, 0.336, 'color: #F9F528','color: #0ACB53'],
]
var data = google.visualization.arrayToDataTable(bar_chart_data);
var formatCurr = new google.visualization.NumberFormat({pattern: '$#,##0'});
formatCurr.format(data, 1);
formatCurr.format(data, 2);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}, 3, // <-- include style column
2, {
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
}, 4 // <-- include style column
]);
var options = {
title: "Live individual material cost break-up (%)",
width: 600,
height: 400,
bar: {
groupWidth: "95%"
},
legend: {
position: "none"
},
isStacked: 'percent',
hAxis: {
title: 'Percentage',
textStyle: {
fontSize: 8,
fontName: 'Muli',
bold: false,
},
titleTextStyle: {
fontSize: 12,
fontName: 'Muli',
bold: true,
}
},
vAxis: {
title: 'Material',
textStyle: {
fontSize: 10,
bold: false
},
titleTextStyle: {
fontSize: 12,
bold: true
}
},
};
var chart = new google.visualization.BarChart(document.getElementById("material_bar_chart"));
chart.draw(view, options);
}
</script>
</head>
<body>
<div id="material_bar_chart" style="width: 900px; height: 500px;"></div>
</body>
</html>

Related

Display annotation on Google Chart

I have a code that generates a google column chart but want to fix 3 things:
Show annotation on top of each stack.
Remove the scales generated on the right side of the graph shown in the image.
There are only three legend colors but it display nine colors. Just display colors of Actual Current, Actual Saving and Actual Time.
Thanks in advance.
Output image
<script type="text/javascript">
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
isStacked: true,
theme: 'material',
width: 800,
height: 480,
annotations: {
style: 'line',
textStyle: {
bold: true,
color: "#000",
fontSize: 18,
auraColor: 'transparent'
},
alwaysOutside: true,
stem:{
color: 'transparent',
},
},
legend: {
position: 'bottom',
textStyle: {
bold: true,
color: "#000",
fontSize: 18,
auraColor: 'transparent'
}
},
//styles: ['color: #ee8800;opacity: 0.2;', 'color: #dd7790;opacity: 0.2;', 'color: #ff9900;opacity: 0.2;'],
// colors: ['#FF00FF', '#d2691e', '#a9a9a9'],
fillOpacity: 0.7,
bar: {
width: 28
},
vAxis: {
textPosition: 'none'
},
series: {
0: {//['#FF00FF', '#d2691e', '#a9a9a9']
targetAxisIndex: 0,
color: '#FF00FF',
annotations: {
// style: 'line',
alwaysOutside: true,
stem: {
//color: "transparent",
length: 15
},
textStyle: {
bold: true,
color: "#000",
fontSize: 18,
auraColor: 'transparent'
}
}
},
1: {
targetAxisIndex: 0,
color: '#d2691e'
},
2: {
targetAxisIndex: 0,
color: '#a9a9a9',
},
3: {
targetAxisIndex: 1,
color: '#FF00FF'
},
4: {
targetAxisIndex: 1,
color: '#d2691e'
},
5: {
targetAxisIndex: 1,
color: '#a9a9a9'
},
6: {
targetAxisIndex: 2,
color: '#FF00FF'
},
7: {
targetAxisIndex: 2,
color: '#d2691e'
},
8: {
targetAxisIndex: 2,
color: '#a9a9a9'
}
},
theme: 'material'
};
var data = new google.visualization.DataTable();
data.addColumn('string', 'Quarter');
data.addColumn('number', 'ActualCurrent');
data.addColumn('number', 'ActualSaving');
data.addColumn('number', 'ActualTime');
data.addColumn('number', 'PlanCurrent');
data.addColumn('number', 'PlanSaving');
data.addColumn('number', 'PlanTime');
data.addColumn('number', 'StategyCurrent');
data.addColumn('number', 'StrategySaving');
data.addColumn({ type: 'string', role: 'annotation' });
data.addColumn('number', 'StrategyTime');
data.addColumn({ type: 'string', role: 'annotation' });
data.addRows([
['2001', 9866, 333, 721, 163, 986, 333, 263, 386,'386', 733,'733'],
['2002', 1633, 231, 539, 125, 986, 333, 463, 186,'186', 253,'253'],
['2003', 1255, 819, 123, 197, 986, 333, 893, 586,'586', 933,'933'],
['2004', 1977, 536, 613, 231, 986, 333, 463, 186,'186', 833,'833']
]);
var container = document.getElementById('chart_div');
var chart = new google.charts.Bar(container);
// move annotations
google.visualization.events.addListener(chart, 'ready', function () {
var chartLayout = chart.getChartLayoutInterface();
var yLocation = chartLayout.getYLocation(0) + options.annotations.textStyle.fontSize;
var observer = new MutationObserver(function () {
Array.prototype.forEach.call(container.getElementsByTagName('text'), function (annotation) {
if ((annotation.getAttribute('text-anchor') === 'middle') &&
(parseInt(annotation.getAttribute('font-size')) === options.annotations.textStyle.fontSize)) {
var rotate = 'rotate(270 ' + annotation.getAttribute('x') + ' ' + yLocation + ')';
annotation.setAttribute('y', yLocation);
annotation.setAttribute('transform', rotate);
}
});
});
observer.observe(container, {
childList: true,
subtree: true
});
});
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
<div id="chart_div" style="width: 100%; height: 100%;"></div>

Google Charts Vertical Combo vhaxis

I have a Google Charts combo chart, I have configured the position of the chart vertically.
I could not add labels to the top and bottom values, nor could I display the values for the top.
How can I display the top and bottom values and also add a label, the label for the top values is 'percentage' and for the bottom values is 'USD'.
This is my actual code:
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Papua New Guinea', 'percentage', 'total'],
['2004/05', 165, 938, 522, 998, 45, 614.6],
['2005/06', 135, 1120, 599, 1268, 88, 682],
['2006/07', 157, 1167, 587, 807, 97, 623],
['2007/08', 139, 1110, 615, 968, 15, 609.4],
['2008/09', 136, 691, 629, 1026, 66, 569.6]
]);
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, {
legend: {
position: 'bottom',
alignment: 'left'
},
title : 'material production',
vAxis: {},
hAxis: {},
height: 420,
orientation: 'vertical',
seriesType: 'bars',
series: {
0: {
pointSize: 5,
type: 'bars',
},
1: {
pointSize: 5,
type: 'bars'
},
2: {
pointSize: 5,
type: 'bars'
},
3: {
pointSize: 5,
type: 'bars'
},
4: {
pointSize: 5,
type: 'line'
},
5: {
pointSize: 5,
type: 'line'
}
}
});
},
packages: ['corechart']
});
I have this jsfiddle which is where I am testing what I need.
https://jsfiddle.net/cruano2/3gpsa9Lo/2/
are you trying to add axis titles?
vAxis: {title: 'Percentage'},
hAxis: {title: 'USD'},
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Papua New Guinea', 'percentage', 'total'],
['2004/05', 165, 938, 522, 998, 45, 614.6],
['2005/06', 135, 1120, 599, 1268, 88, 682],
['2006/07', 157, 1167, 587, 807, 97, 623],
['2007/08', 139, 1110, 615, 968, 15, 609.4],
['2008/09', 136, 691, 629, 1026, 66, 569.6]
]);
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, {
legend: {
position: 'bottom',
alignment: 'left'
},
title : 'material production',
vAxis: {title: 'Percentage'},
hAxis: {title: 'USD'},
height: 420,
orientation: 'vertical',
seriesType: 'bars',
series: {
0: {
pointSize: 5,
type: 'bars',
},
1: {
pointSize: 5,
type: 'bars'
},
2: {
pointSize: 5,
type: 'bars'
},
3: {
pointSize: 5,
type: 'bars'
},
4: {
pointSize: 5,
type: 'line'
},
5: {
pointSize: 5,
type: 'line'
}
}
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Line Chart hAxis formatting problematic in Firefox

See image hAxis labels:
The hAxis labels are wrapping onto two lines, their values are, for example, 10.09 with no spaces. But on narrower screens its wrapping onto two lines, this is in Firefox.
In Chrome it works much better. This is how it looks in Chrome:
var options = {
height: 314,
areaOpacity: 0.18,
enableInteractivity: false,
isStacked: true,
hAxis: {
textStyle: {
color: '#919fa9',
fontName: 'Proxima Nova',
fontSize: 11,
italic: false
}
},
vAxis: {
slantedText: true,
minValue: 0,
textPosition: 'out',
title: 'Revenue',
titleTextStyle: {
fontSize: 14
},
textStyle: {
color: '#919fa9',
fontName: 'Proxima Nova',
fontSize: 11,
italic: false
},
baselineColor: '#eff1f2',
gridlines: {
color: '#eff1f2',
count: 15
}
},
lineWidth: 2,
colors: ['#00a8ff'],
curveType: 'function',
pointSize: 5,
pointShapeType: 'circle',
pointFillColor: '#008ffb',
backgroundColor: {
fill: '#ffffff',
strokeWidth: 0,
},
chartArea: {
left: 60,
top: 10,
width: '100%',
height: 260
},
fontSize: 11,
fontName: 'Proxima Nova',
tooltip: {
trigger: 'selection',
isHtml: true
},
seriesType: 'bars',
series: {
0: { color: '#2db56e' },
1: { color: '#cc0000' },
2: {
type: 'line',
color: '#00a8ff',
pointSize: 4,
pointShapeType: 'circle'
}
}
};
How can I improve the appearance of the Firefox version? Because at present its very hard to read
try setting the following option to 1 --> hAxis.maxTextLines
hAxis: {
maxTextLines: 1,
...
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['date', 'revenue'],
['10.01', 20],
['10.02', 30],
['10.03', 40],
['10.04', 50],
['10.05', 60],
['10.06', 70],
['10.07', 80],
['10.08', 90],
['10.09', 100],
['10.10', 120],
['10.11', 130],
['10.12', 150],
['10.13', 200],
['10.14', 220],
['10.15', 230],
['10.16', 240],
['10.17', 250],
['10.18', 260],
['10.19', 270],
['10.20', 280],
['10.21', 280],
['10.22', 290],
['10.23', 320],
['10.24', 340],
['10.25', 350],
['10.26', 360],
['10.27', 370],
['10.28', 380],
['10.29', 390],
['10.30', 400],
['10.31', 420]
]);
var options = {
height: 314,
areaOpacity: 0.18,
enableInteractivity: false,
isStacked: true,
hAxis: {
maxTextLines: 1,
textStyle: {
color: '#919fa9',
fontName: 'Proxima Nova',
fontSize: 11,
italic: false
}
},
vAxis: {
slantedText: true,
minValue: 0,
textPosition: 'out',
title: 'Revenue',
titleTextStyle: {
fontSize: 14
},
textStyle: {
color: '#919fa9',
fontName: 'Proxima Nova',
fontSize: 11,
italic: false
},
baselineColor: '#eff1f2',
gridlines: {
color: '#eff1f2',
count: 15
}
},
lineWidth: 2,
colors: ['#00a8ff'],
curveType: 'function',
pointSize: 5,
pointShapeType: 'circle',
pointFillColor: '#008ffb',
backgroundColor: {
fill: '#ffffff',
strokeWidth: 0,
},
chartArea: {
left: 60,
top: 10,
width: '100%',
height: 260
},
fontSize: 11,
fontName: 'Proxima Nova',
tooltip: {
trigger: 'selection',
isHtml: true
},
seriesType: 'bars',
series: {
0: { color: '#2db56e' },
1: { color: '#cc0000' },
2: {
type: 'line',
color: '#00a8ff',
pointSize: 4,
pointShapeType: 'circle'
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How do I remove non-integers in the axis of a plotly.js graph?

return {
height: 210,
title: title,
autosize: true,
width: '100%',
font: {
size: 10,
family: "Roboto"
},
showlegend: false,
margin: {
l: 40,
r: 10,
b: 35,
t: 22,
pad: 0
},
xaxis: {
nticks: 6,
title: "Score",
linecolor: '#cccccc',
zerolinewidth: 0,
zerolinecolor: '#fff'
},
yaxis: {
title: "Number of students",
linecolor: '#cccccc',
zerolinewidth: 0,
zerolinecolor: '#eeeeee',
range: [0, numStudents]
},
bargap: 0.5
};
This is including half steps as well 1.5 and so on. I am using plotly.js and this is what I see:
You can force Plotly to use defined distances between the axis' ticks by setting dtick in the layout options of your axis, i.e. in your case it would be
{yaxis: {dtick: 1}}
See below for an example of no layout settings vs fixed dtick.
var trace1 = {
x: ['A', 'B', 'C'],
y: [1, 3, 2],
mode: 'markers',
type: 'bar'
};
Plotly.newPlot('myPlot1', [trace1], {yaxis: {dtick: 1}});
Plotly.newPlot('myPlot2', [trace1]);
<script src="https://cdn.plot.ly/plotly-latest.min.js">
</script>
<div id = "myPlot1" ></div>
<div id = "myPlot2" ></div>

Google Charts - Full width for line chart

I use combo google chart to display my data and goals on the graph like this:
I want to display goal lines on a full width of the graph, like this:
Here is what I've tried but with no luck:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Month', 'RUH %', 'SJA %', 'Goal 30', 'Goal 60'],
['GKP', 16, 93, 30, 60],
['HKP', 13, 11, 30, 60],
['SKP', 15, 11, 30, 60],
['AEV', 19, 80, 30, 60],
['AE', 63, 69, 30, 60]
]);
// Create and draw the visualization.
var ac = new google.visualization.ComboChart(document.getElementById('visualization'));
ac.draw(data, {
title : 'RUH og SJA måloppnåelse',
width: 600,
height: 400,
chartArea: {'width': '90%', 'height': '80%'},
colors: ["blue", "green"],
legend: { position: 'bottom' },
vAxis: {title: ""},
hAxis: {title: ""},
seriesType: "bars",
series: {2: {type: "line", visibleInLegend: false, color: "red"}, 3:{type: "line", visibleInLegend: false, color: "red"}}
});
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="visualization" style="width: 600px; height: 400px;"></div>
</body>
</html>
How can I achieve this?
To extend the lines to the edge of the chart, you have to use a continuous type axis, and extend your data set by one row before and after your existing data. You can use a DataView to convert your string labels to formatted numbers, and then use the hAxis.ticks option to set the axis labels:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Month', 'RUH %', 'SJA %', 'Goal 30', 'Goal 60'],
['', null, null, 30, 60],
['GKP', 16, 93, 30, 60],
['HKP', 13, 11, 30, 60],
['SKP', 15, 11, 30, 60],
['AEV', 19, 80, 30, 60],
['AE', 63, 69, 30, 60],
['', null, null, 30, 60]
]);
var ticks = [];
// ignore the first and last rows
for (var i = 1; i < data.getNumberOfRows() - 1; i++) {
ticks.push({v: i, f: data.getValue(i, 0)});
}
var view = new google.visualization.DataView(data);
view.setColumns([{
type: 'number',
label: data.getColumnLabel(0),
calc: function (dt, row) {
return {v: row, f: dt.getValue(row, 0)};
}
}, 1, 2, 3, 4]);
var range = view.getColumnRange(0);
var offset = 0.5; // change this value to adjust the padding to the left and right of the columns in the chart
// Create and draw the visualization.
var ac = new google.visualization.ComboChart(document.getElementById('visualization'));
ac.draw(view, {
title : 'RUH og SJA måloppnåelse',
width: 600,
height: 400,
chartArea: {
width: '90%',
height: '80%'
},
colors: ["blue", "green"],
legend: {
position: 'bottom'
},
vAxis: {
title: ""
},
hAxis: {
title: "",
ticks: ticks,
viewWindow: {
min: range.min + offset,
max: range.max - offset
},
gridlines: {
// hide vertical gridlines to match discrete chart display
color: 'transparent'
}
},
seriesType: "bars",
series: {
2: {
type: "line",
visibleInLegend: false,
color: "red"
},
3:{
type: "line",
visibleInLegend: false,
color: "red"
}
}
});
}
see working example here: http://jsfiddle.net/asgallant/J2u3n/

Categories