Multiple X axis labels google charts - javascript

How can I create multiple x Axis labels using the google charts API?
Im trying to create a bar graph right now with the main x axis labels as "products" and the individual bars relating to the products in question. However, I would like to segregate a set of 'n' products (data coming in from a database) by months.
Essentially I want a main X Axis label "product" and a dividing line between each set of products and a label underneath this set of bar graphs pertaining to the products grouping together each 'product set' by month
Thanks in advance to anyone who can help me with this!!

Sample double x-axis bar chart with google charts. Taken from their api documentation which can be found here:
Double x-axis bar chart
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Galaxy', 'Distance', 'Brightness'],
['Canis Major Dwarf', 8000, 23.3],
['Sagittarius Dwarf', 24000, 4.5],
['Ursa Major II Dwarf', 30000, 14.3],
['Lg. Magellanic Cloud', 50000, 0.9],
['Bootes I', 60000, 13.1]
]);
var options = {
width: 800,
chart: {
title: 'Nearby galaxies',
subtitle: 'distance on the left, brightness on the right'
},
bars: 'horizontal', // Required for Material Bar Charts.
series: {
0: { axis: 'distance' }, // Bind series 0 to an axis named 'distance'.
1: { axis: 'brightness' } // Bind series 1 to an axis named 'brightness'.
},
axes: {
x: {
distance: {label: 'parsecs'}, // Bottom x-axis.
brightness: {side: 'top', label: 'apparent magnitude'} // Top x-axis.
}
}
};
var chart = new google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
};
</script>
</head>
<body>
<div id="dual_x_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Not sure if that is exactly what you want to do, but if not let us know and we can modify this slightly.

Related

Show label and percentage in Google pie chart

I would like to show label and percentage in Google pie chart. Is there any way to do it? In the docs, I found that it is possible to modify text with pieSliceText option. Possible values are:
label - show name of data (e. g. Apples)
value - show absolute value (e. g. 7)
percentage - show percentage value (e. g. 50%)
value-and-percentage - show both value and percentage (e. g. 7 (50%))
But is there something like label-and-percentage to show something like that Apples (50%)?
the only config option that will show both the label & percentage is for the legend...
legend: {
position: 'labeled'
},
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Tasks', 'Completed'],
['Morning', 28],
['Afternoon', 43],
['Evening', 80],
['Night', 161]
]);
var options = {
width: 900,
height: 400,
title: 'Tasks Completed',
pieHole: 0.5,
colors: ['#008000', '#ffbf00', '#FF0000','#4E6282'],
pieSliceText: 'value',
sliceVisibilityThreshold :0,
fontSize: 17,
legend: {
position: 'labeled'
},
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
You can show either label or percentage on pie charts. Look at the pieSliceText options here.
But if this is your requirement and you HAVE to show label and percentage both on pie chart that you can try this:
set, pieSliceText: 'value' in options.
And then pass formatted value in data of chart by calculating the percentage of every slice data and passing the label + percentage as formatted value:
data.addRows([
['Label', {v:value, f:'formatted value'}],
]);
here v: is the value of chart
and f: is formatted value of chart which in your case will be label +
percentage.
Eg:
[chartlabels, {v: chartvalue, f: chartlabels+" "+((100 * chartvalue) / totalofvalues).toFixed(2)+"%"}]

How to change the bar chart orientation in Google Charts

I need to draw two bar charts facing each other in one page. (The chart on the left faces right, and the one on the right faces left).
But with Google Charts, I only managed to make both charts face right.
Is it possible to implement? What should I do?
using a 100% stacked chart, you can get the bars to align to the right
then color the first series transparent,
and manipulate the data to reveal the proper length
then when the chart's 'ready' event fires,
you can move around the chart elements,
such as the y-axis, and the order of the x-axis labels
first, you need to allow enough room on the left,
for the original y-axis labels to print
otherwise they will be cutoff, i.e.
Canis Major Dwarf vs. Canis Maj...
then need to leave enough room on the right,
by limiting the chartArea, otherwise cutoff and simply not visible, i.e.
Canis Major Dwarf vs. Canis M
might be easier, providing your own labels
this should give you something to tweak on...
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Galaxy', 'Distance', 'Brightness'],
['Canis Major Dwarf', 10, 20],
['Sagittarius Dwarf', 20, 40],
['Ursa Major II Dwarf', 40, 50],
['Lg. Magellanic Cloud', 60, 80],
['Bootes I', 80, 120]
]);
var options = {
isStacked: 'percent',
colors: ['transparent', 'magenta'],
legend: {
position: 'bottom'
},
chartArea: {
left: 200,
width: 400
},
width: 800
};
var container = document.getElementById('dual_x_div');
var chart = new google.visualization.BarChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var labels = container.getElementsByTagName('text');
var hAxisLabels = [];
Array.prototype.forEach.call(labels, function (text, index) {
switch (text.getAttribute('text-anchor')) {
// move y axis labels
case 'end':
text.setAttribute('x', parseFloat(text.getAttribute('x')) + 540);
break;
// save x axis labels
case 'middle':
// save x position here
// otherwise, x position will change
// before you know where the next should have been
hAxisLabels.push({
text: text,
x: parseFloat(text.getAttribute('x'))
});
break;
}
});
// swap label positions
hAxisLabels.forEach(function (label, index) {
label.text.setAttribute('x', hAxisLabels[hAxisLabels.length - index - 1].x);
});
});
chart.draw(data, options);
};
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dual_x_div"></div>

Google Charts legend is not correctly displayed

I am creating google chart and my legend is not being folded into pages.
My code is somthing like
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
google.load("visualization", "1.1", { packages: ["bar", "table"] });
var chart;
var table;
var graphOptions = {
title: 'Liczba ekspozycji w miesiÄ…cu',
pointSize: 5,
vAxis: { viewWindowMode: "explicit", viewWindow: { min: 0 } },
height: '500'
};
$(function() {
chart = new google.charts.Bar(document.getElementById('chart_div'));
});
var maxGraphLines = 50;
function refreshGraph(data) {
chart.draw(dataTableForGrap, google.charts.Bar.convertOptions(graphOptions));
}
</script>
<div id="chart_div" ></div>
and what I get is:
as you can see the labels for legend are going all the way down even behind the div. They should be paged into pages but this does not happen. Any help will be appreciated. Thanks.
The new "material" bar chart does not yet support paging or scrolling of legend items. Until it does, you might try using the corechart ColumnChart with the option { theme: 'material' } to get the material colors and fonts.

Google column chart with logarithmic rendering values below baseline

Problem
I am rendering a column chart using the Google charts javascript API where some it is possible that some of the values can be under 1%. When I render these values the bar is being rendered below the baseline of the graph. If these values are >= 1 then they are rendered correctly. According the Google charts API reference on logScale: "If true, makes the vertical axis a logarithmic scale Note: All values must be positive." - they are positive.
Here is an image of what I am experiencing.
Question
How can I get all values which are 0 < v <1 above the x axis?
I have had some success with multiplying all percentages by 100 (so from decimal format it would be 10000), then specificly setting each columns label to be the correct percentage however the y axis (vertical axis) then has values for the gridlines that do not correctly represent the data set.
As you can see the very small value is being rendered below. Do note that this isnt just for a data set that has a very large value and a very small one. I experienced this with a data set of ~100 with all values < 4%.
To Reproduce
JSFiddle for your convience here
HTML:
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
Javascript:
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales'],
['2004', .23],
['2005', 1.23],
['2006', 88],
['2007', 1.12],
['2008', 9.65]
]);
var options = {
title: 'Company Performance',
vAxis: {title: 'Year', titleTextStyle: {color: 'red'}, logScale: true}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Found answer in another question, but the solution is to use an undocumented feature in the options : scaleType:"mirrorLog"
var options = {
title: 'Company Performance',
vAxis: {title: 'Year', titleTextStyle: {color: 'red'}, logScale: true, scaleType:"mirrorLog"}
};
Full details here: ScaleType Google question

jQPlot Horizontal Bar Graph - assign names to Y Axis

I figured it out:
I was not including the jqplot.CategoryAxisRenderer. Once I included that, I was able to get it working.
Thanks, everyone!
UPDATE:
My code works in JSFiddle, so it's a CSS problem I'm having. Please disregard.
I'm trying to create a fairly simple bar chart in jQPlot. I'm expecting two horizontal bars, one on top of the other. Both are equal to 1 on the X axis. I want the Y axis to have the labels 'In Progress' for the top bar, and 'Apr 2014' for the bottom bar. I have tried numerous combinations. If I do not specify Ticks, then I see the two bars. Specifying Ticks, or using the desired labels as the Y axis data point just shows both labels overlapping with no bars. (ignore the setTimeout) Thanks in advance.
Here's the code:
var data = [[1,1],[1,2]];
var ticks = ['In Progress','Mar 2014'];
$(function () {
setTimeout(function(){
var plot1 = jQuery.jqplot ('chartdiv', [data],
{
seriesDefaults: {
renderer:$.jqplot.BarRenderer,
rendererOptions: {
barDirection: 'horizontal'
},
},
axes: {
yaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
}
}
});
},
100);
});
I have modified the JsFiddle given by Batu Zet previously adding following lines in order to label your bar chart here :
series: [
{
pointLabels:{
show:true,
labels:['Apr 2014', 'Apr 2014']
}
},
{
pointLabels:{
show:true,
labels:['In Progress', 'In Progress']
}
}
]
P.S : The labels are duplicated for each serie in order to display the same label for two points in a serie.

Categories