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.
Related
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.
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.
i am using google chart api to show a chart on a bootstrap modal with framework Laravel, i'm having an issue because i'm not beein able to change the colour of the bar and put one blue and the other one green, another issue is that at the right it only put me the name of une of the bars(RX).
Here is my js code:
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
// google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart(nombre, unidad, tipo, valor, media) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'RX');
data.addColumn({type: 'string', role: 'annotation'});
data.addRows([
['Tú', parseInt(valor), valor+' '+unidad],
['Media', parseFloat(media), parseInt(media)+' '+unidad],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,1,2]);
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(view, {
// height: 400,
// width: 600,
series: {
0: {
type: 'bars'
},
1: {
type: 'line',
color: 'grey',
lineWidth: 0,
pointSize: 0,
visibleInLegend: false
}
},
vAxis: {
maxValue: 100,
minValue: 0,
}
});
$("#myModalLabel").empty();
$("#myModalLabel").append(tipo+" - "+nombre);
$("#modalChart").modal();
}
Here is the chart that i get:
you can write your drawchart function like this
<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
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%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
</script>
For more https://developers.google.com/chart/interactive/docs/gallery/columnchart#labeling-columns
I'm trying to add a vertical line so that there can be a visual distinction for when an element exceeds the value.
Thanks
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Difference", {
role: "style"
}],
["FOLDERADDUPDATE", 2.29, "#e5e6e2"],
["NOTEUPDATE", 3.63, "silver"],
["DELETENOTE", 1.12, "e5e4e7"],
["NOTEUPDATEANDFOLDER", 5.02, "color: #e5e4e2"],
["FOLDERREMOVEUPDATE",.082,"color:e5e5e2"],
["PENDINGEVENT", 0,"color:e5e4e4"]
]);
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: "95%"
},
legend: {
position: "none"
},
};
var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
chart.draw(view, options);
}
</script>
The following example demonstrates how to draw an additional vertical line
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Difference", {
role: "style"
}],
["FOLDERADDUPDATE", 2.29, "#e5e6e2"],
["NOTEUPDATE", 3.63, "silver"],
["DELETENOTE", 1.12, "e5e4e7"],
["NOTEUPDATEANDFOLDER", 5.02, "color: #e5e4e2"],
["FOLDERREMOVEUPDATE",.082,"color:e5e5e2"],
["PENDINGEVENT", 0,"color:e5e4e4"]
]);
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: "95%"
},
legend: {
position: "none"
}
};
var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
chart.draw(view, options);
drawVAxisLine(chart, 3.0); //set x value where line shoud be located
}
function drawVAxisLine(chart,value){
var layout = chart.getChartLayoutInterface();
var chartArea = layout.getChartAreaBoundingBox();
var svg = chart.getContainer().getElementsByTagName('svg')[0];
var xLoc = layout.getXLocation(value)
svg.appendChild(createLine(xLoc,chartArea.top + chartArea.height,xLoc,chartArea.top,'#00cccc',4)); // axis line
}
function createLine(x1, y1, x2, y2, color, w) {
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', x1);
line.setAttribute('y1', y1);
line.setAttribute('x2', x2);
line.setAttribute('y2', y2);
line.setAttribute('stroke', color);
line.setAttribute('stroke-width', w);
return line;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="barchart_values"></div>
Maybe this?
Insert in options ticks: and enter desired values (like 1,3,5,7 in this example)
hAxis: {
title: 'My Values',
ticks: [1,3,5,7],
minValue: 0
}
JSFiddle
I have data in the form of
[[X, Y, {role: "annotation"}], [1,2, "something"], ...,...]
that I pass to
var data = google.visualization.arrayToDataTable(dataPattern); and plot with
var material = new google.charts.Bar(document.getElementById('distribution-over-range'));
material.draw(data, google.charts.Bar.convertOptions(options));
The annotations fail to appear. Any idea why?
google.charts.Bar component does not support annotations role but you could utilize google.visualization.BarChart from corechart package for that purpose as demonstrated below:
//google.load("visualization", "1.1", {packages:["bar"]});
google.load("visualization", "1.1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.arrayToDataTable([
['Opening Move', 'Percentage', { role: "style" }, { role: 'annotation' }],
["King's pawn (e4)", 44, "#b87333",'43%'],
["Queen's pawn (d4)", 31, "silver", '31%'],
["Knight to King 3 (Nf3)", 12, "gold", '12%'],
["Queen's bishop pawn (c4)", 10, "color: #e5e4e2", '10%'],
['Other', 3, "green", '3%']
]);
var options = {
title: 'Chess opening moves',
width: 900,
legend: { position: 'none' },
chart: { title: 'Chess opening moves',
subtitle: 'popularity by percentage' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
//var chart = new google.charts.Bar(document.getElementById('top_x_div'));
var chart = new google.visualization.BarChart(document.getElementById("top_x_div"));
chart.draw(data, options);
};
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="top_x_div" style="width: 640px; height: 480px;"></div>