I have a basic google chart:-
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Year', 'Austria', 'Belgium', 'Czech Republic'],
['2006', 1600652, 4604684, 940478],
['2007', 1968113, 4013653, 1037079],
['2008', 1901067, 6792087, 1037327]
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
hAxis: {title: "Year"}}
);
}
I want to be able to specify the border color and width etc.
Can you tell me how to use the API commands:-
backgroundColor.stroke,
backgroundColor.strokeWidth,
i.e How do I add these API calls.
Thanks
You can send the settings for both the stroke color and strokeWidth with the rest of you options, similar to how you've specified the title for the hAxis:
backgroundColor: {
stroke: '#000',
strokeWidth: '2'
}
That would give the chart a black 2pixel border, demo on jsfiddle.
Related
I would like to make a google chart that highlights different regions continents, or countries based on a particular grouping.
The problem is I can't figure the best way to show both continents and countries.
For instance, I'd like to have two highlighted entries: Europe and Japan.
I can use the below JS code to attempt this:
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Region', 'Label', {role: 'tooltip', p:{html:true}}],
['150', 1, 'Europe'],
['Japan', 2, 'Japan']
]);
var options = {
resolution: 'continents',
}
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
geochart.draw(data, options);
};
The above code partly works- Europe is properly highlighted and labelled. However, because resolution is set to 'continents' Japan does not get highlighted. If I set resolution to 'countries' the opposite problem occurs.
So the real question:
Is there a way to highlight both Europe and Japan individually with one array entry each, or do I have to put every single European country in the list to also have Japan highlighted?
yes, you would need to put every single European country in the list to also have Japan highlighted
another option might be to draw two charts, one on top of the other,
using the following config options to allow the bottom one to show thru.
backgroundColor: 'transparent',
datalessRegionColor: 'transparent',
however, this would suppress the tooltip on the bottom chart.
see following working snippet for an example...
google.charts.load('current', {packages:['geochart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Region', 'Label', {role: 'tooltip', p:{html:true}}],
['150', 1, 'Europe']
]);
var options1 = {
backgroundColor: 'transparent',
datalessRegionColor: 'transparent',
resolution: 'continents'
}
var geochart1 = new google.visualization.GeoChart(
document.getElementById('visualization1')
);
geochart1.draw(data1, options1);
var data2 = google.visualization.arrayToDataTable([
['Region', 'Label', {role: 'tooltip', p:{html:true}}],
['Japan', 2, 'Japan']
]);
var options2 = {
backgroundColor: 'transparent',
datalessRegionColor: 'transparent',
resolution: 'countries'
}
var geochart2 = new google.visualization.GeoChart(
document.getElementById('visualization2')
);
geochart2.draw(data2, options2);
}
.geo {
left: 0px;
position: absolute;
top: 0px;
width: 100%;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="geo" id="visualization1"></div>
<div class="geo" id="visualization2"></div>
note: jsapi should no longer be used to load the charts library,
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. The last update, for security purposes, was with a pre-release of v45. Please use the new gstatic loader.js from now on.
this will only change the load statement, see above snippet...
I'm hoping to find a way, using Keen's visualization library, to integrate Google Chart's ChartRangeFilter (https://developers.google.com/chart/interactive/docs/gallery/controls#chartrangefilter). The section in Keen's docs (https://github.com/keen/keen-js/blob/master/docs/visualization.md#line-chart) related to line charts doesn't seem to afford any chart wrappers or controls.
In short, is there any way to render a line chart with a ChartRangeFilter using Keen out of the box? Or would I have to ask for the raw data and do the charting for myself?
Looking at the sample code and Google chart's instructions from https://developers.google.com/chart/interactive/docs/gallery/controls#using-controls--and-dashboards you'll need to combine code from Google into the charting portion after your result is computed from Keen.
You will first prepare your data (in your case, using the data result returned from Keen IO), then create a dashboard, and lastly draw/render the components (including the chartRangeFilter). Drawing the range filter for the chart is a modification to the existing visualization that can be graphed with Keen IO.
// Load the Google Visualization API and the controls package.
google.charts.load('current', {packages:['corechart', 'table', 'gauge', 'controls']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(init);
function init(){
client
//Run your Keen Query/Analysis Call
.query('count', {
event_collection: 'add_to_carts',
timeframe: {
start: '2016-09-01',
end: '2016-09-12'
},
interval: 'hourly',
timezone: 'US/Pacific'
//group_by: 'product_name'
})
.then(function(res){
var chart = new Dataviz()
.data(res)
drawDashboard(chart.data());
})
.catch(function(err){
console.log('err');
});
}
// Callback that creates and populates a data table,
// instantiates a dashboard, a range slider and a pie chart,
// passes in the data and draws it.
function drawDashboard(keenDataTable) {
// Create our data table.
var data = google.visualization.arrayToDataTable(keenDataTable);
// Create a dashboard.
var dashboardEl = document.getElementById('dashboard_div');
var dashboard = new google.visualization.Dashboard(dashboardEl);
// Create a range slider, passing some options
var chartRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'control_div',
'options': {
'filterColumnIndex': 1,
'ui': {
'chartType': 'LineChart',
'chartOptions': {
'chartArea': {'height': '20%', 'width': '90%'},
'hAxis': {'baselineColor': 'none'}
}
}
}
});
// Create a pie chart, passing some options
var lineChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'chart_div',
'options': {
// Use the same chart area width as the control for axis alignment.
'chartArea': {'height': '80%', 'width': '90%'},
'hAxis': {'slantedText': false},
'vAxis': {'viewWindow': {'min': 0, 'max': 50}},
'legend': {'position': 'none'}
}
});
// Establish dependencies, declaring that 'filter' drives 'lineChart',
// so that the chart will only display entries that are let through
// given the chosen slider range.
dashboard.bind(chartRangeSlider, lineChart);
// Draw the dashboard.
dashboard.draw(data);
Here's a link to a JavaScript fiddle that runs this code and shows the Keen analysis result being rendered along with the Google range finder component:
http://jsfiddle.net/kuqod2ya/4/
This code sample uses the newest keen-analysis.js & keen-dataviz.js libraries. To access the Google Chart additional options include loader.js.
I am using Google Charts in my project where I get data from the controller as in Model Attribute. But when I see the Line Chart the x-axis comes in a reverse order.
Here's what I did:
var data4 = new google.visualization.DataTable();
data4.addColumn('string', 'Date');
data4.addColumn('number','Balance');
<c:forEach var="details" items="${details}">
data4.addRow(["${details.date}", ${details.amount}]);
</c:forEach>
var options4 = {
width: 600,
height: 400,
title: 'Amount',
hAxis: { titleTextStyle: {color: '#333'}, direction:-1, slantedText:true, slantedTextAngle:45},
vAxis: {minValue: 1000},
};`
var chart4 = new google.visualization.LineChart(document.getElementById('chart4'));
chart4.draw(data4, options4);
I get date in x-axis but in the reverse order in which it is added in the rows. I think adding of rows is like adding at the start not appending, How do I make it in the right order?
Can anyone help me.
Thanks in advance.
To track number of visitor comes through which website and do some analysis on the same. We are creating a column chart to show the analysis report in graphical form.
All the things are showing correctly on chart, but we are showing website name on haxis. As website name is too long like "www.google.com", www.facebook.com, this label are being cut off on haxis.
Code to draw chart is given below:
function createTodayChart(chartData){
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sources');
data.addColumn('number', 'Total Sales');
for (var i in chartData){
//alert(chartData[i][0]+'=>'+ parseInt(chartData[i][1]));
data.addRow([chartData[i][0], parseInt(chartData[i][1])]);
}
var options = {
legend: {position:'top'},
hAxis: {title: 'Sources', titleTextStyle: {color: 'black'}, count: -1, viewWindowMode: 'pretty', slantedText: true},
vAxis: {title: 'Total Sales (in USD)', titleTextStyle: {color: 'black'}, count: -1, format: '$#'},
colors: ['#F1CA3A']
};
var chart = new google.visualization.ColumnChart(document.getElementById('my_div'));
chart.draw(data, options);
}
Data in chartData variable is in array form as:
var chartData = [];
cartData.push('www.w3school.com', 106);
cartData.push('www.google.com', 210);
Width and height of "my_div" are 350px and 300px respectively. We have also attached screen shot of this issue given below:
Can anyone help me that how can we prevent this cutting issue. Or, Is any method available in google chart API to prevent this?
Waiting for solution.
This is an always recurring issue in google visualization, in my opinion :( There are a few "tricks" one can experiment with : chartArea and hAxis.textPosition. Here is your code in a jsFiddle with the following chartData, reproducing the problem above :
var chartData = [
['www.facebook.com', 45],
['http://www.google.com', 67],
['www.stackoverflow.com', 11]
];
fiddle -> http://jsfiddle.net/a6WYw/
chartArea can be used to adjust the upper "padding" taking space from the legend / hAxis below along with the internal height of the bars (the chart itself without axis and legend). For example
chartArea: {
top: 55,
height: '40%'
}
Will shrink the chartArea, giving room for the legend on the hAxis.
fiddle -> http://jsfiddle.net/Swtv3/
My personal favourite is to place the hAxis legend inside the chart by
hAxis : { textPosition : 'in' }
This will honor both short and long descriptions, and does not make the chart looking too "weird" when there is a few very long strings.
fiddle -> http://jsfiddle.net/7HBmX/
As per comment - move the "in" labels outside the chart. There is to my knowledge no native way to do this, but we can always alter the <svg>. This can be a difficult task, but in this case we know that the only <text> elements who has the text-anchor="middle" attribute is the h-axis labels and the overall h-axis description. So
var y, labels = document.querySelectorAll('[text-anchor="middle"]');
for (var i=0;i<labels.length-2;i++) {
y = parseInt(labels[i].getAttribute('y'));
labels[i].setAttribute('y', y+30);
}
to move the labels outside the chart. demo -> http://jsfiddle.net/970opuu0/
I'm wondering if it's possible to display a kind of data table in GEO Charts. I have this code:
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawMarkersMap);
function drawMarkersMap() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Count');
data.addRow(["AT",141]);
data.addRow(["BE",8]);
data.addRow(["CH",42]);
data.addRow(["DE",98]);
data.addRow(["ES",942]);
data.addRow(["GR",30]);
data.addRow(["HQ",104]);
data.addRow(["HU",30]);
data.addRow(["LU",10]);
data.addRow(["NL",153]);
data.addRow(["PL",53]);
data.addRow(["PT",102]);
data.addRow(["RU",266]);
data.addRow(["SE",13]);
data.addRow(["TR",228]);
var options = {
displayMode: 'regions',
region: '150',
colorAxis: {colors: ['#ffa3b5', 'red']},
tooltip: { textStyle: { fontName: '"Verdana"', fontSize: 14 } },
legend: {textStyle: {color: 'black', fontSize: 10}},
keepAspectRatio: false,
height: 300,
width: 550
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div_02'));
chart.draw(data, options);
}
As I have some special countries (like HQ) and Turkey (that is not in region 150), I would like to a datatable or legend to the geochart.
Is this possible or do I have to make a table charts and put it somewhere else on the website?
Cheers & Thx in Advance
Alex
You cannot add a dataTable to the geoChart using the native Google Visualization API. A GeoChart is a GeoChart and a DataTable is a DataTable. However, you can create a linked GeoChart and DataTable on the same page using the same data taking advantage of the Dashboard controls and chartwrappers.
If you get fancy with your CSS, you can even hover the <div> with the table over the GeoChart, or otherwise find a way to make it look like they are the same chart.