Google Charts only using first color - javascript

I am having trouble with Google Charts Bar Chart option to change colors of my bars - I have 3 bars and 3 colors listed in the options, but the bars are only showing the first color. Any ideas why?
function drawChart2() {
var chartdata = new google.visualization.arrayToDataTable([
['Vote Choice', 'Votes'],
[$scope.PropVotes[3].description, $scope.PropVotes[3].numVotes],
[$scope.PropVotes[4].description, $scope.PropVotes[4].numVotes],
[$scope.PropVotes[5].description, $scope.PropVotes[5].numVotes]
]);
var options = {
title: $scope.Propositions[1].Title,
legend: {
position: 'top'
},
colors: ['#002c58', '#69BE28', '#A5ACAF'],
chartArea: {
width: '100%',
height: '100%'
},
bars: 'horizontal',
animation: {
startup: true,
duration: 5000,
easing: 'linear'
}
};
var chartName = 'chart_div2'; //' + $scope.PropVotes.id;
var chart = new google.charts.Bar(document.getElementById(chartName));
chart.draw(chartdata, options);
}

Related

Google Charts - Can you align columns in a column chart to the center of the chart?

Is there a way using the column chart provided by the Google charts javascript api to center columns in the middle of the chart rather than having large amounts of space between each column? I can accomplish this by grouping the values together but I lose the label under the column.
Here's a pic of what I'm trying to accomplish:
Here's what I have so far:
google.charts.load('current', { packages: ['corechart', 'bar'] })
google.charts.setOnLoadCallback(drawColColors)
function drawColColors() {
const data = google.visualization.arrayToDataTable([
['Number', 'Price'],
['1', 1900000],
['2', 1800000],
['3', 1500000]
])
const options = {
width: '100%',
height: 400,
colors: ['red'],
vAxis: { minValue: 0, format: '$###,###,###' },
enableInteractivity: false,
bar: { groupWidth: 45 },
legend: { position: 'none' }
}
const chart = new google.visualization.ColumnChart(document.getElementById('chart'))
chart.draw(data, options)
}
Codesandbox: https://codepen.io/anon/pen/GworqG
bar.groupWidth is the only config option that will specifically address column alignment
(in this manner)
however, instead of a number...
bar: {groupWidth: 45},
you can also use a percentage.
This won't necessarily move the columns, but it will make them larger, bringing them closer together.
bar: {groupWidth: '90%'},
see following working snippet for an example...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Number', 'Price'],
['1', 1900000],
['2', 1800000],
['3', 1500000]
])
var options = {
width: '100%',
height: 400,
colors: ['red'],
vAxis: {minValue: 0, format: '$###,###,###'},
enableInteractivity: false,
bar: {groupWidth: '90%'},
legend: { position: 'none' }
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart'))
chart.draw(data, options)
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
another option would be to use actual numbers (1), rather than strings ('1'), on the x-axis.
this enables additional config options you can use to push the columns closer to the center.
for instance, setting the viewWindow will allow you to add space between the visible columns and the edges.
hAxis: {
viewWindow: {
min: -2,
max: 6
}
}
by default, a continuous axis (numbers) will display grid lines,
whereas a discrete axis (strings) will not.
these can be removed, or hidden, with the following options.
baselineColor: 'transparent',
gridlines: {
color: 'transparent'
},
see following working snippet for another example...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Number', 'Price'],
[1, 1900000],
[2, 1800000],
[3, 1500000]
])
var options = {
width: '100%',
height: 400,
colors: ['red'],
vAxis: {minValue: 0, format: '$###,###,###'},
enableInteractivity: false,
legend: {position: 'none'},
hAxis: {
baselineColor: 'transparent',
gridlines: {
color: 'transparent'
},
ticks: data.getDistinctValues(0),
viewWindow: {
min: -2,
max: 6
}
}
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart'))
chart.draw(data, options)
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

Want to add top padding on annotation text in bar chart in Google Chart (Visualization)

I am using Google Chart's bar graph chart. There are annotation for every bar at the top, inside of the bar and I want create more space (more than default) between bar top line and annotation text. I have not find any way to create top padding (or top margin) around annotation text.
Here is my code:
var data = google.visualization.arrayToDataTable([
[USER_AVERAGE, 'User Average', { role: 'style' }],
['SANDRA COOMBS', 8.6, '#008FBE'],
['STEVE ADAMS', 4.3, '#008FBE'],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 2,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}]);
var options = {
legend: {
position: 'none'
},
chartArea: { width: width, height: height, right: right },
isStacked: true,
orientation: orientation.orientation,
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("averageDaysChart"));
chart.draw(view.toDataTable(), options);
there are no config options for annotation padding, position, or the like...
however, you can move them manually on the chart's 'animationfinish' event
but, a MutationObserver must be used,
because the chart will move them back on interactivity,
such as when you hover the column.
see following working snippet for an example of moving the annotations...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['USER_AVERAGE', 'User Average', { role: 'style' }],
['SANDRA COOMBS', 8.6, '#008FBE'],
['STEVE ADAMS', 4.3, '#008FBE'],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 2,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}]);
var options = {
legend: {
position: 'none'
},
//chartArea: { width: width, height: height, right: right },
isStacked: true,
//orientation: orientation.orientation,
fontSize: '12',
fontName: 'OpenSans-Regular',
hAxis: {
viewWindowMode: 'maximized',
},
vAxis: {
viewWindowMode: 'maximized',
},
animation: {
startup: true,
duration: 1500,
easing: 'out',
},
};
var container = document.getElementById("averageDaysChart");
var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'animationfinish', function () {
moveAnnotations();
var observer = new MutationObserver(moveAnnotations);
observer.observe(container, {
childList: true,
subtree: true
});
});
var originalY = {};
function moveAnnotations() {
var labels = container.getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label) {
if ((!isNaN(parseFloat(label.textContent))) && (label.getAttribute('text-anchor') === 'middle')) {
if (!originalY.hasOwnProperty(label.textContent)) {
originalY[label.textContent] = parseFloat(label.getAttribute('y'));
}
label.setAttribute('y', originalY[label.textContent] + 20);
}
});
}
chart.draw(view.toDataTable(), options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="averageDaysChart"></div>
No need for an animation hook or MutationObserver, just use good old fashioned CSS for this.
With Column and Bar charts, you only want to apply the "padding" to the annotation if it's placed within the bar itself. It's only placed inside the bar if the annotation text fits in the bar. When placed inside, it's given a white text color, so let's target that.
#averageDaysChart text[fill="#ffffff"] {
transform: translateY(10px);
}

How to set Google Chart height based on number of rows?

I have a Google stacked bar chart that pulls data from a database and draws charts based on said data. I was able to search around and find a way to dynamically set the height based on the number of rows - but for one of my search filters, the charts look way off.
The code is below and works for 4 out of 5 of my filters, but in the 5th filter the number of rows becomes much larger (around 40-50).
Code:
var paddingHeight = 40;
var rowHeight = data.getNumberOfRows() * 50;
var chartHeight = rowHeight + paddingHeight;
var options = {
titlePosition: 'none',
width: 1400,
height: chartHeight,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '50%' },
isStacked: true,
hAxis: {
title: 'Business Hours (excluding weekends & holidays)'
},
colors: ['#0066ff', '#33cc33', '#ffcc00', '#ff0000'],
annotations: {
alwaysOutside: true,
textStyle: {
color: '#000000'
}
}
}
Produces the following results. This first image is what 4 of my 5 filters looks like.
The second image is the one in question that shows I'm clearly doing something wrong.
What is the cause of this and how can I resolve it?
Edit: I suspect my issue is one of the following:
Either my data rows are not being counted correctly as I refresh the page with the latest search parameters or I have a problem with how my divs are set up and interacting with each other. I've tried adjusting the math behind the chartHeight and removing the padding and it seems to have the same effect either way. Am I on the right track or is there something else I'm missing?
need to set options for both height and chartArea.height
here, recommend using rowHeight for chartArea.height
var paddingHeight = 40;
var rowHeight = data.getNumberOfRows() * 50;
var chartHeight = rowHeight + paddingHeight;
var options = {
titlePosition: 'none',
width: 1400,
height: chartHeight,
chartArea: {
height: rowHeight,
},
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '50%' },
isStacked: true,
hAxis: {
title: 'Business Hours (excluding weekends & holidays)'
},
colors: ['#0066ff', '#33cc33', '#ffcc00', '#ff0000'],
annotations: {
alwaysOutside: true,
textStyle: {
color: '#000000'
}
}
}
you'll want to leave some room for the legend, y-axis, etc...
chartArea has the following properties
top
left
height
width
you'll want to set top to 20 or something if legend is on top

How can I increase length of y-axis in Google Charts?

I am using Google Charts. The JavaScript which I am using:
function drawChart3() {
var data3 = google.visualization.arrayToDataTable([
['Day', 'Sales','exp'],
['4-APRIL-16', 1000,200],
['5-APRIL-16', 1170,300],
['6-APRIL-16', 660,400],
['7-APRIL-16', 1030,500],
['8-APRIL-16', 60,4100],
['9-APRIL-16', 130,5020],
['10-APRIL-16', 60,4100],
['11-APRIL-16', 130,5020],
]);
var options3 = {
title: 'Company Performance',
curveType: 'function',
legend: {
position: 'bottom'
}
};
var chart3 = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart3.draw(data3, options3);
If you see the image of the page the y axis labels of date is not well aligned. How can I align them properly?
You have two options available. The dimensions of a chart will be set by:
The dimensions of the containing element, or:
By setting the height and width properties in the options for the chart.
The following will show you both approaches adapted from your code.
http://jsbin.com/televe/edit?html,css,js,console,output
Either:
#curve_chart {
width: 200px;
}
or
var options4 = {
title: 'Company Performance',
curveType: 'function',
height: 400,
width: 300,
legend: {
position: 'bottom'
}
};
The widths are up to you.
Reference:
https://developers.google.com/chart/interactive/docs/basic_customizing_chart#specify-options

Google chart api explorer vs. selecthandler

I have problem with using Google.charts api... i have chart drawing function like this:
function columnDraw(sectionname) {
var data = google.visualization.arrayToDataTable(array);
var view = new google.visualization.DataView(data);
var options = {
title: "Activity of users",
bar: {groupWidth: "100%"},
legend: {position: "top"},
height: 300,
// explorer: {
//maxZoomOut:0
//maxZoomIn: 50,
// keepInBounds: true,
// axis: 'horizontal'
// },
hAxis: {
title: 'Amount of activity',
minValue : 0,
format: '0'
},
vAxis: {
title: 'Amount of users',
minValue : 0,
format: '0'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById(sectionname));
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
document.getElementById("input0").value = data.getValue(selectedItem.row, 0);
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(view, options);
}
I want to choose parts of chartcolumn by cklicing on them, but i have a problem with zooming. This code works but once I uncomment the explorer part, selectHandler function wont work properly. Can anyone tell me whats wrong with it?
You're missing a ","
maxZoomOut:0,

Categories