enable lables for each cell in bar chart - javascript

I am trying to set each bar chart cell with lables of A, B and C for all my data to be shown on chart. I tried with data.addColumn('string', 'Alphabets'); but it is not working out.
It shall be easy but i am missing something.
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
var raw_data = [
['A', 40],
['B', 17],
['C', 7]
];
data.addColumn('string', 'Columns');
for (var i = 0; i < raw_data.length; ++i) {
data.addColumn('number', raw_data[i][0]);
}
data.addRows(1);
data.setValue(0, 0, 'row');
for (var i = 0; i < raw_data.length; ++i) {
data.setValue(0, i + 1, raw_data[i][1]);
}
// Set chart options
var options = {'title':'Megafon 27/10 2011',
'width':1300,
'height':600,
'colors' : ['red', 'blue', 'green']
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

You are not formatting your data correctly.
Series names are in separate columns (each column will add a new color to the chart, and a new item to the legend).
Value labels (the names of the X-axis categories) are in the first column of each row. You are doing them backwards, therefore there are no axis labels.
For instance, this code:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Label', 'Data'],
['A', 10],
['B', 20],
['C', 40],
['D', 80]
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,{});
}
Creates this graph:
However, you want to have a different color for each series (which is bad visualization practice). To do that you need to have 4 different columns to get 4 different colors.
To do this you need to reformat your data as follows:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Label', 'Color 1', 'Color 2', 'Color 3', 'Color 4'],
['A', 10, null, null, null],
['B', null, 20, null, null],
['C', null, null, 40, null],
['D', null, null, null, 80]
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,{series: [{color: 'red'},{color: 'orange'},{color: 'yellow'},{color: 'green'}]});
}
This comes out like this:
The issue then is that you have 4 different series in the legend, although they only represent one type of data (and this is why it is bad visualization practice!).
You also get a bit of an ugly looking graph, but that can be fixed with setting the options to isStacked: true.
At any rate, I'd just keep the data as it is in your array, and not fiddle with color. But your mileage may vary.

Related

google chart with multiple dates

I have multiple collections of data I want to display in a single google chart. Each series is a collection of CPM's with a date:
for instance:
series A[
'2016-09-01' => 2.08023,
'2016-09-04' => 2.01123
];
series B[
'2016-09-01' => 1.99324,
'2016-09-02' => 2.00112
];
Note that the dates in the two series are not the same. I want to draw these two graphs in a single google graph. How should I format the data rows (if this is possible at all).
I have made a JSFiddle with what I thought would be a way to go, but adding a null in the data table doesn't work, I get two dots for the first series where I'm expecting a line. How can I make google chart draw the line instead of the dots?
in the fiddle, the data is setup correctly
however, since there is a null value is Series A due to the different dates
need to use configuration option interpolateNulls: true
from the documentation...
interpolateNulls
Whether to guess the value of missing points. If true, it will guess the value of any missing data based on neighboring points. If false, it will leave a break in the line at the unknown point.
see following working snippet...
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'X');
data.addColumn('number', 'series a');
data.addColumn('number', 'series b')
data.addRows([
[new Date( 1472688000000 ), 2.08023, 1.99324],
[new Date( 1472774400000 ), null, 2.00112],
[new Date( 1472947200000 ), 2.01123, null]
]);
var options = {
interpolateNulls: true
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Adding filters and charting the results in Google Visualization

I have a Water Usage Sample Google Spreadsheet with Month, Day, Time, Usage, and Gallons columns.
I'd like to build a dashboard with a Month filter, Day filter, Usage filter, Column Chart and Pie Chart. By default (with no filter selections made), I'd like the column chart to display a sum of gallons by month and the pie chart to display the total usage breakdown.
If a specific month is selected in the Month filter, I'd like the column chart to then display the sum of gallons for each day within that month and the pie chart to display the usage breakdown for that month. If a specific month and day is selected in the month filter and day filter, then I would like the column chart to then display each "gallons" entry by time for that month/day and the pie chart to display the usage breakdown for that month/day. If a specific usage is selected in the usage filter, I'd like the column chart to operate in the same manner as previously described, while only factoring the data for that specific usage. The pie chart would obviously just show 100% of that usage.
Here is the fiddle I've been working on.
google.load('visualization', '1.1', {
'packages': ['corechart']
});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var opts = {sendMethod: 'auto'};
// Replace the data source URL on next line with your data source URL.
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1oQTmYteohmVxiBReIyh_tRuOLIx6CXwgw0MuNw5jTTw/gviz/tq?sheet=Sheet1&headers=1&range=A1:E2000', opts);
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var columnData = google.visualization.data.group(data, [{
column: 1,
type: 'date'
}], [{
column: 4,
label: 'Gallons',
aggregation: google.visualization.data.sum,
type: 'number'
}]);
var pieData = google.visualization.data.group(data, [{
column: 3,
type: 'date'
}], [{
column: 4,
label: 'Gallons',
aggregation: google.visualization.data.sum,
type: 'number'
}]);
// Set chart options
var options = {
'title': 'WaterUsage',
'width': 400,
'height': 300
};
// Instantiate and draw our chart, passing in some options.
var columnChart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
columnChart.draw(columnData, options);
var pieChart = new google.visualization.PieChart(document.getElementById('chart_div2'));
pieChart.draw(pieData, options);
This was mainly derived from this thread. Any ideas?

Google Charts - No data available - Able to display a blank chart?

How can I still have Google Charts still show a line chart if my data array looks like this?
[['Date','Line']]
i.e. just the axis are defined. Most of my charts have data imported but some have nil on the data. I would like to display a blank chart. With data above I get an error message instead of a chart.
Here is code in my view
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(#{#visiting_spread_movement_array});
var options = {
title: 'Point Spread Movements for #{#event.visiting_team}'
};
var chart = new google.visualization.LineChart(document.getElementById('show-spread-visiting'));
chart.draw(data, options);
}
Well, to draw the chart you need at least one data point. To archieve this, you could use this workaround:
var data = google.visualization.arrayToDataTable([
[{
f: 'Date',
type: 'date' // wont work whithout this
}, {
f: 'Line',
type: 'number' // wont work whithout this
}], ]);
var options = {
title: 'Company Performance'
};
if (data.getNumberOfRows() == 0) { // if you have no data, add a data point and make the series transparent
data.addRow([new Date(), 0])
options.series = {
0: {
color: 'transparent'
}
}
}
Full fiddle: http://jsfiddle.net/qaLgh955/

Create date histogram chart with google histogram

How to create Google Histogram Chart [1] that works with dates?
I've placed sample code (with working number and non-working date examples): http://jsfiddle.net/Qquse/417/ and code below [2]
[1] https://developers.google.com/chart/interactive/docs/gallery/histogram
[2]
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function str_to_utcdate(d) {
return new Date(d.substr(0, 4), d.substr(5, 2) - 1, d.substr(9, 2));
}
function drawChart() {
var data = google.visualization.arrayToDataTable([
['item', 'date'],
['a', str_to_utcdate('2001-07-01')],
['b', str_to_utcdate('2001-07-01')],
['c', str_to_utcdate('2001-07-01')], ]);
var chart = new google.visualization.Histogram(document.getElementById('chart_div1'));
chart.draw(data);
var data = google.visualization.arrayToDataTable([
['item', 'date'],
['a', 10],
['b', 20],
['c', 30], ]);
var chart = new google.visualization.Histogram(document.getElementById('chart_div2'));
chart.draw(data);
}
5 years now and Histograms still don't support dates. Since I ain't got time and I need my stuff done, I made a workaround (so ugly it hurts) but works.
First, I defined a format just to put a keyword at the start of each label. In my case, since I have only one chart in my page, I just used the keyword 'date'.
const keyword = 'date';
const options = {
// ...
hAxis: {
format: `'${keyword}'#`
},
}
If you have multiple charts in your page and you want them to behave differently, you might want to define different keyword to each one.
Now, using query selector, I selected all the label elements that are of my interest
let labels = Array.from(document.querySelectorAll('#chart svg g:nth-of-type(3) g:nth-of-type(3) g text'));
In my case, my chart was set in a DIV with id 'chart'. If you're using any other id, just replace #chart with your id;
Then I will filter only the labels which start with my keyword 'date'
labels = labels.filter(g => g.innerHTML.startsWith(keyword));
With that, I replace the innerHTML of each element to the date format I wish.
labels.forEach(g => {
const date = new Date(+g.substring(keyword.length));
// you can apply any format method you wish
// .toLocaleDateString()
g.innerHTML = date.toLocaleDateString();
// moment.js
g.innerHTML = moment(date).format('DD/MM/YYYY HH:MM');
});
Also, I'm using interactive charts, so the labels refresh on each user interaction. Therefore, I put everything inside an interval, and the final result is as follows:
const keyword = 'date';
const options = {
// ...
hAxis: {
format: `'${keyword}'#`
},
}
// ... chart setup
setInterval(() => {
let labels = Array.from(document.querySelectorAll('#chart svg g:nth-of-type(3) g:nth-of-type(3) g text'));
labels = labels.filter(g => g.innerHTML.startsWith(keyword));
labels.forEach(g => {
const date = new Date(+g.substring(keyword.length));
g.innerHTML = date.toLocaleDateString();
});
}, 100);
Use this answer with caution. Using query selectors to modify third party generated content is very unsafe because it relies on the hope that the third-party developers won't modify the way the content is generated.
Try out this column chart:
public histogramChart: GoogleChartInterface = {
chartType: 'ColumnChart',
dataTable: [
['Date', 'Number'],
[new Date(2015, 1, 1), 5],
[new Date(2015, 1, 2), 5.1],
[new Date(2015, 1, 3), 6.2],
[new Date(2015, 1, 4), 7]
];,
//opt_firstRowIsData: true,
options: {
title: 'Shooting history',
legend: { position: 'none' },
colors: ['#4285F4'],
},
};

Google chart tools get rid of horizontal spacing

I have a histogram that i want to render with ColumnCharts, I followed the tutorial and did it and got this as an result:
Note the spacing at the either end of the graph (particularly the left side as the right side have some columns that's very small)
I tried to use viewWindow but it seems to have no particular effect. Here's the code (coffeescript) that's used to draw it. The data has been snipped to save space as they are fairly big
data = google.visualization.arrayToDataTable([
labels, bardata
])
# The labels are ["x", "label for each column" ....]
# bardata is [number, number, number] (these numbers are the height of the column)
chart = new google.visualization.ColumnChart(document.getElementById("enrollment-total-chart"))
chart.draw(data,
width: 400
height: 300
hAxis:
title: "Number of students"
vAxis:
title: "Number of schools"
viewWindow:
max: "auto"
min: 0
viewWindowMode: "explicit"
legend: position: "none"
)
The issue is likely with your data. For instance, if I make this chart:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['x', 'A', 'B', 'C', 'D', 'E', 'F'],
['A', 0, 0, 3, 4, 5, 0],
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,
{width:600, height:400,
hAxis: {title: "Year"}}
);
}
There is a lot of white space at the left/right of the chart due to the zeroes (my guess is that you have a lot of zeroes in the extremes).
I'm a bit confused also by your data -- you say you have many different rows, but a histogram is just a pair of X Y data, so the use of color (differentiating the series) is a bit different than a standard histogram.
If the above doesn't answer your question, could you please include your data so that we can understand a bit better what you're trying to do (anonymized if necessary).

Categories