Google column chart with logarithmic rendering values below baseline - javascript

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

Related

How to display a single data point on Google Area OR Line chart

I've tried every configuration possible to get a Google Area Chart to display a single point but nothing has worked. I'm also totally open to any solutions using the Google Line Chart as long as it has a filled area. However, I couldn't find a solution for making this work with a line chart either.
Already tried setting the pointSize as well as setting the pointSize conditionally if there is only a single row. Tried numerous different ways of configuring the chart including.
var data = new google.visualization.DataTable();
data.addColumn('date', 'Updated');
data.addColumn('number', 'Amount');
data.addRow([new Date(1548266417060.704),100]);
AND
var mets = [['Updated', 'Amount'], [new Date(1548266417060.704),100]];
var data = google.visualization.arrayToDataTable(mets);
Area Chart Example JSFiddle
Line Chart Example JSFiddle
This Line Chart would need the area below the line filled in but I haven't been able to determine how to do so with this API
Example of the chart I'm trying to achieve using CanvasJs but I'm trying to implement it with Google Visualization API and allow for a single point to be shown if there is only a single point on the chart.
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704),100],
//[new Date(1548716961817.513),100],
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
pointSize: 5,
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I'm expecting the chart to display a single point when there is only one data row. As you can see by the JSFiddle when there is a single row nothing appears but as soon as you uncomment the second row everything works just fine.
there is a bug with the most recent version of google charts,
when the x-axis is a continuous axis (date, number, not string, etc.),
and only one row exists in the data table,
you must set an explicit view window on the axis --> hAxis.viewWindow
to use a date type with only one row,
first, use data table method --> getColumnRange
this will return an object with min & max properties for the x-axis
then we can increase the max and decrease the min by one day,
and use that for our view window.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704),100]
]);
var oneDay = (24 * 60 * 60 * 1000);
var dateRange = data.getColumnRange(0);
if (data.getNumberOfRows() === 1) {
dateRange.min = new Date(dateRange.min.getTime() - oneDay);
dateRange.max = new Date(dateRange.max.getTime() + oneDay);
}
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {color: '#333'},
viewWindow: dateRange
},
pointSize: 5
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
you'll notice if we go back to an old version ('45'),
a single date row displays without issue...
google.charts.load('45', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704),100]
]);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {color: '#333'},
},
pointSize: 5
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I dont know if you understod but the date format you are passing is wrong, so when you write Date() it return the current date formatted as string.
now if we understand that much then the currect way of writing the date array should be
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704).toString(),100],
]);
This will return the date formatted as string.
and the library will accept it.
if you are still want to pass on an object then you need to specify the dataTable column as Date.
read here for more information
https://developers.google.com/chart/interactive/docs/datesandtimes

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)+"%"}]

Multiple X axis labels google charts

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.

How to get a continuous ColumnChart?

I'm using a ColumnChart to represent the elevation in a map, as suggested by Google.
However, the columns are separated by spaces, and that renders ugly white spaces between the
columns, like in Google's own example:
https://developers.google.com/maps/documentation/javascript/examples/elevation-paths
Is there a way to tell the column chart to make columns that fill up the whole space? I would like something like this:
http://4.bp.blogspot.com/-4I8oi3WqY5o/UIZnzbXql_I/AAAAAAAAAcE/GO4wl6I2-lM/s1600/Charts.png
I suspect that the only way is with lots of points.
My code:
var option = {
legend: 'none',
backgroundColor: 'transparent',
colors: ["#C9CFF5"],
titleColor: '#C9CFF5',
focusBorderColor: '#00AA00',
titleY: 'Elevation (m)',
bar: { groupWidth: '100%' }
}
// Build data
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation (m):');
for (var i = 0; i < trackmarks.length; i++) {
data.addRow(['', trackaltis[i]]);
}
// Draw the chart using the data within its DIV.
chart = new google.visualization.ColumnChart(document.getElementById('elevation_chart'));
chart.draw(data, option);
My code is pretty standard: same as Google's, same result.
Thanks!
You can specify option:
bar: {groupWidth: "100%"}
bar.groupWidth: Percentage of the available width for each group (e.g. '20%'), where '100%' means that groups have no space between them
Update: That example uses old version of column charts which loads package columnchart
google.load("visualization", "1", {packages:["columnchart"]});
The latest code for column chart is loaded using corechart:
google.load('visualization', '1', {packages: ['corechart']});
Change that and example should work as expected without spaces.

How to set y axis format and remove y axis border line of columnchart package in google api chart?

I am using google api chart in column chart package created to chart. but in this chart cannot be remove y axis line and cannot be set y axis format.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["columnchart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
width: 400,
height: 240,
legend: 'none',
bar: { groupWidth: '50%' }
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
Don't use the 'columnchart' package - it is old and deprecated. Use the newer 'corechart' package instead:
google.load('visualization', '1', {packages:['corechart']});
That enables the options you need to format your chart the way you want it. See the complete list of options here. By default, with the 'corechart' package, there will not be a line on the y-axis in your sample code. You can format the axis values using the vAxis.format option:
vAxis: {
format: '$#,###'
}
In this google api chart using columnchart package. column chart package is one of the oldest package, in this package there is no more customization. so we are not set y axis format and remove y axis border line.
google.load("visualization", "1", {packages:['columnchart']});
the newest version of google api chart package is core chart package. that is
google.load('visualization', '1', {packages:['corechart']});
suppose we are using this package. possible for y axis format and remove y axis border line.
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['x', 'Report'],
['2013-12-20 10:20:30', 1],
['2013-12-20 10:30:30', 2],
['2013-12-20 12:20:30', 4],
['2013-12-21 10:20:30', 5],
['2013-12-21 20:20:30', 2],
['2013-12-22 20:20:30', 2],
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data, {
width: 500, height: 400,
vAxis: {title: "Health Chart",ticks: [{v:5, f:"Healthy"},{v:2, f:"Unhealthy"},{v:4, f:"Better"},{v:1, f:"Not Good"}]},}
);
}
google.setOnLoadCallback(drawVisualization);
google.setOnLoadCallback(drawVisualization);
You can run this code on google code playground (ie https://code.google.com/apis/ajax/playground/#line_chart)
And change vAxis according to your options.

Categories