Google Visualizations (Charts) API: Change which axis the legend uses? - javascript

See here: https://jsfiddle.net/1cLpukxx/1/
As you can see, the legend is the Density value. I think that's because all I'm doing is this:
legend: { position: "right" }
I'd like the legend to be the elements, with the colour that they are in the charts.
I feel like this should be easy, however I haven't found it in any examples (using the x-axis legend as the side-legend). I feel like this is because I don't know what to search for but I digress...

The style column used in the example overrides the legend, which is why the position is set to --> 'none'
One option would be to change the rows to columns, as in the following example.
This creates separate series and allows setting an array for colors in the configuration options.
However, this causes other issues, such as the spacing of the columns.
google.charts.load("current", {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Metal", "Copper", "Silver", "Gold", "Platinum"],
["Copper", 8.94, null, null, null],
["Silver", null, 10.49, null, null],
["Gold", null, null, 19.30, null],
["Platinum", null, null, null, 21.45]
]);
var view = new google.visualization.DataView(data);
view.setColumns([
0,
1, {calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"},
2, {calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"},
3, {calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation"},
4, {calc: "stringify",
sourceColumn: 4,
type: "string",
role: "annotation"},
]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
legend: {alignment: "right"},
colors: ['#b87333', 'silver', 'gold', '#e5e4e2']
};
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

How to force the Google Chart Legend to show Row values?

I hope this question can be understood as I find this topic rather tricky to explain. What I am looking for is a solution for a Google (Column) Chart, in which the chart shows both, X-Axis and legend with values, like a pie chart sometimes does. Most examples I found simply turned off the legend, though.
Here is what I got so far: First example of the fitting x axis:
The legend just shows 'Density', which makes sense, but I am looking for all the metals in the legend as well. So I switched the order of the dataset, to end up with this one:
And here the x axis shows density instead of the metals. So what I am looking for is something like this:
Either way, be it the manipulation of the legend or the manipulation of the axis works for me. Any ideas how to proceed?
Sources
First version
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Density", { role: "style" } ],
["Copper", 8.94, "#b87333"],
["Silver", 10.49, "silver"],
["Gold", 19.30, "gold"],
["Platinum", 21.45, "color: #e5e4e2"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
My Fiddle: https://jsfiddle.net/927pjLvb/2/
Second version:
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Copper", "Silver", "Gold", "Platinum"],
["Density", 8.94, 10.49, 19.30, 21.45],
]);
var view = new google.visualization.DataView(data);
view.setColumns([
0,
1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2,
{ calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation" },
3,
{ calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation" },
4,
{ calc: "stringify",
sourceColumn: 4,
type: "string",
role: "annotation" }
]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
colors: ['#b87333', 'silver', 'gold', '#e5e4e2'],
bar: {groupWidth: "95%"},
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
My fiddle: https://jsfiddle.net/8jaL9kf3/
starting with the second version, leave the x-axis label blank.
var data = google.visualization.arrayToDataTable([
['Element', 'Copper', 'Silver', 'Gold', 'Platinum'],
['', 8.94, 10.49, 19.30, 21.45]
]);
on the chart's 'ready' event,
copy the labels from the legend,
and place them under the bars,
using chart method --> getChartLayoutInterface()
the layout interface has method --> getBoundingBox(id)
this method returns the coordinates of chart elements,
by passing the id of the element.
in this case, we want to know the coordinates of the bars.
the id of each bar is structured as follows.
'bar#0#0' // <-- first bar
where the first 0 is the series number, and the second row number.
once we know the coordinates of the bars,
we can place the copied labels under them.
see following working snippet...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Element', 'Copper', 'Silver', 'Gold', 'Platinum'],
['', 8.94, 10.49, 19.30, 21.45]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}, 2, {
calc: 'stringify',
sourceColumn: 2,
type: 'string',
role: 'annotation'
}, 3, {
calc: 'stringify',
sourceColumn: 3,
type: 'string',
role: 'annotation'
}, 4, {
calc: 'stringify',
sourceColumn: 4,
type: 'string',
role: 'annotation'
}]);
var options = {
title: 'Density of Precious Metals, in g/cm^3',
width: 600,
height: 400,
colors: ['#b87333', 'silver', 'gold', '#e5e4e2'],
bar: {groupWidth: '95%'},
};
var container = document.getElementById('columnchart_values');
var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'ready', function (gglClick) {
// chart svg
var svg = container.getElementsByTagName('svg')[0];
// chart layout
var chartLayout = chart.getChartLayoutInterface();
// get all chart labels, chart title will be first, legend labels next
var labels = container.getElementsByTagName('text');
// process each series in the data table
for (var series = 1; series < data.getNumberOfColumns(); series++) {
// get bar bounds
var barBounds = chartLayout.getBoundingBox('bar#' + (series - 1) + '#0');
// copy legend label
var barLabel = labels[series].cloneNode(true);
// padding above label
var labelPadding = 4;
// center align label
barLabel.setAttribute('text-anchor', 'middle');
// set label x,y coordinates
barLabel.setAttribute('x', barBounds.left + (barBounds.width / 2));
barLabel.setAttribute('y', barBounds.top + barBounds.height + parseFloat(barLabel.getAttribute('font-size')) + labelPadding);
// add label to chart svg
svg.appendChild(barLabel);
}
});
chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchart_values"></div>
note: the above example assumes the chart will have a title option.

How to draw vertical axis in google charts

I am using gooogle charts. When I include constant values in the third & fourth column in my chart it shows me as horizontal lines. Please suggest how to draw it as vertical lines as shown in the image belows
I found this,
Hereby a complete working fiddle to show you how it can be done:
http://jsfiddle.net/NC37X/1345/
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// example copied from Google Visualization API playground,
// modified for category axis annotations
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'x');
data.addColumn({type: 'string', role: 'annotation'});
data.addColumn({type: 'string', role: 'annotationText'});
data.addColumn('number', 'Cats');
data.addColumn('number', 'Blanket 1');
data.addRow(["A", null, null, 1, 1, ]);
data.addRow(["B", null, null, 2, 0.5]);
data.addRow(["C", null, null, 4, 1]);
data.addRow(["D", null, null, 8, 0.5]);
data.addRow(["E", null, null, 7, 1]);
data.addRow(["F", null, null, 7, 0.5]);
data.addRow(["G", 'Foo', 'Foo annotation', 8, 1]);
data.addRow(["H", null, null, 4, 0.5]);
data.addRow(["I", null, null, 2, 1]);
data.addRow(["J", null, null, 3.5, 0.5]);
data.addRow(["K", 'Bar', 'Bar annotation', 3, 1]);
data.addRow(["L", null, null, 3.5, 0.5]);
data.addRow(["M", null, null, 1, 1]);
data.addRow(["N", null, null, 1, 0.5]);
// Create and draw the visualization.
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {
curveType: 'function',
width: 500,
height: 400,
vAxis: {
maxValue: 10
},
annotations: {
style: 'line'
}
});
}

Animation is not working for third bar in stacked bar chart in Google Charts (Visualization)

I am using Google Charts (Google Visualization), it was working fine . But now, I am facing a weird problem in animation. It is a stacked bar chart. First two columns (bars) is animating flawlessly but third column (bar) is coming at once, animation is not working for the last bar (third column).
I have tried with total 2 bars and now 2nd bar's animation is not working (came at once). It is clear that problem is in last bar. Is it a flaw in stacked bar chart from Google Chart's end?
Here is my code:
var data = google.visualization.arrayToDataTable([
['Status', awating, not_interested, interested, { role: 'annotation' }],
['SANDRA COOMBS', 2, 4, 2, ''],
['VINCENT ODA', 2, 2, 2, ''],
]);
arTotal = niTotal = iTotal = 0;
for (var i = 0; i < data.getNumberOfRows(); i++) {
if (data.getValue(i, 1) != null) {
arTotal += data.getValue(i, 1);
}
if (data.getValue(i, 2) != null) {
niTotal += data.getValue(i, 2);
}
if (data.getValue(i, 3) != null) {
iTotal += data.getValue(i, 3);
}
}
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2, {
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
},
3, {
calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation"
}]);
var options = {
legend: {
position: 'none'
},
chartArea: { width: width, height: height, right: right },
isStacked: true,
orientation: orientation.orientation,
colors: ['#008FBE', '#BE1E2D', '#00BD90'],
fontSize: '12',
fontName: 'OpenSans-Regular',
hAxis: {
viewWindowMode: 'maximized',
},
vAxis: {
viewWindowMode: 'maximized',
},
animation: {
startup: true,
duration: 1500,
easing: 'out',
},
};
var chart = new google.visualization.ColumnChart(document.getElementById("currentStatusChart"));
google.visualization.events.addListener(chart, 'ready', readyHandler);
chart.draw(view, options);
i've encountered various bugs when using animation on startup,
specifically when a DataView is used to draw the chart
a workaround is to convert the DataView into a DataTable before drawing the chart,
you can use method --> toDataTable()
view.toDataTable()
which does seem to help in this situation,
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Status', 'awating', 'not_interested', 'interested', { role: 'annotation' }],
['SANDRA COOMBS', 2, 4, 2, ''],
['VINCENT ODA', 2, 2, 2, ''],
]);
arTotal = niTotal = iTotal = 0;
for (var i = 0; i < data.getNumberOfRows(); i++) {
if (data.getValue(i, 1) != null) {
arTotal += data.getValue(i, 1);
}
if (data.getValue(i, 2) != null) {
niTotal += data.getValue(i, 2);
}
if (data.getValue(i, 3) != null) {
iTotal += data.getValue(i, 3);
}
}
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2, {
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
},
3, {
calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation"
}]);
var options = {
legend: {
position: 'none'
},
//chartArea: { width: width, height: height, right: right },
isStacked: true,
//orientation: orientation.orientation,
colors: ['#008FBE', '#BE1E2D', '#00BD90'],
fontSize: '12',
fontName: 'OpenSans-Regular',
hAxis: {
viewWindowMode: 'maximized',
},
vAxis: {
viewWindowMode: 'maximized',
},
animation: {
startup: true,
duration: 1500,
easing: 'out',
},
};
var chart = new google.visualization.ColumnChart(document.getElementById("currentStatusChart"));
chart.draw(view.toDataTable(), options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="currentStatusChart"></div>

Can't set width of column in bar chart [duplicate]

This question already has an answer here:
Google Charts show all labels
(1 answer)
Closed 4 years ago.
I'm working with Google Bar Charts. In the left side, I need to add the description of the bars.
Move within USA
Received in New Jersy
Handed over to International
Currier At Sri lanka port
But I can't show the whole sentence in the bar chart. Below I attached the bar chart and the code
google.charts.load("current", {packages: ["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Density", {role: "style"}],
["Move within USA",parseInt(orderObj.RNJ), "color :blue"],
["Received in New Jersy", parseInt(orderObj.HOC), "color :yellow"],
["Handed over to International Currier", parseInt(orderObj.ASP), "color :red"],
["At Sri lanka port", parseInt(orderObj.KWH), "color: green"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2]);
var options = {
title: "",
width: 600,
height: 300,
bar: {groupWidth: "65%"},
legend: {position: "none"}
};
var chart = new google.visualization.BarChart(document.getElementById("chart_divSea1"));
chart.draw(view, options);
How about adjusting it using left and width of chartArea as follows?
var options = {
title: "",
width: 600,
height: 300,
bar: {groupWidth: "65%"},
legend: {position: "none"},
chartArea: {left: 250, width: 300} // Added
};
google.charts.load("current", {packages: ["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var orderObj = {RNJ: 6, HOC: 26, ASP: 6, KWH: 14}; // sample values
var data = google.visualization.arrayToDataTable([
["Element", "Density", {role: "style"}],
["Move within USA",parseInt(orderObj.RNJ), "color :blue"],
["Received in New Jersy", parseInt(orderObj.HOC), "color :yellow"],
["Handed over to International Currier", parseInt(orderObj.ASP), "color :red"],
["At Sri lanka port", parseInt(orderObj.KWH), "color: green"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}, 2]);
var options = {
title: "",
width: 600,
height: 300,
bar: {groupWidth: "65%"},
legend: {position: "none"},
chartArea: {left: 250, width: 300} // Added
};
var chart = new google.visualization.BarChart(document.getElementById("chart_divSea1"));
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_divSea1"></div>
Reference :
Configuration Options
If this was not what you want, I'm sorry.

Google Column Chart: Column height not in proportion to the value

I am using the Google Column Chart to visualize data.
Problem:
Unfortunately with a certain input the heights of the column bars are not in proportion.
Error Reproduction:
I reconstructed this in a simple JsFiddle.
Here is an other example, which contains a working and a not working version.
Question:
How can the issue be fixed, so that the height is proportional to the value differences of my columns.
If for example one column has the value 20.000 and an other 40.000, the height of the first one should be half as high as for the second column.
Thank you so much.
Code examples & images:
Here is my jsFiddleCode:
Html:
<body>
<h1>
Weird height of Google Column Chart Bars.
</h1>
<div id="columnchart_values"></div>
<h1>
Correct height of Google Column Chart Bars.
</h1>
<div id="columnchart_values2"></div>
</body>
Javascript:
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
if( typeof( parts[1] ) != 'undefined' ){
parts[1] = parts[1].substr(0,2);
}
return parts.join(",");
}
function drawChart1() {
var data = google.visualization.arrayToDataTable([
['Quelle', 'Geldbetrag', { role: 'style' }, { role: 'annotation' } ],
['test1', 40000, '#11368A', 'Cu' ],
['test2', 29400, '#000357', 'Ag' ],
['test3', 22193, '#40F020', 'Au' ],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
function drawChart2() {
/*only the data of test 3 changed*/
var data = google.visualization.arrayToDataTable([
['Quelle', 'Geldbetrag', { role: 'style' }, { role: 'annotation' } ],
['test1', 40000, '#11368A', 'Cu' ],
['test2', 29400, '#000357', 'Ag' ],
['test3', 19000, '#40F020', 'Au' ],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values2"));
chart.draw(view, options);
}
google.charts.load('current', {packages: ['corechart'], 'language': 'de'});
google.charts.setOnLoadCallback( function(){
drawChart1();
drawChart2();
} );
The current behavior is to remain backward compatible with the way it used to be years ago. Now it will include the baseline value in the chart if it is "close enough" to the data. But you can force the baseline value of the bars to be included in the chart by simply specifying the baseline value explicitly. For your example, just add:
vAxis: { baseline: 0 }
to your options. See https://jsfiddle.net/2betxw5u/2/
Adding: vAxis: {minValue: 0, format: '€ #,###'} to the options solves the problem.

Categories