Adding different links to each column (Google Charts) - javascript

I need to add different links which open another page to every column on a column chart.
Clicks to every different columns should open another window.
My current template only works if columns are seperate from each other, i want to have it works even columns are contiguous.
My current template is that:
<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(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['test', 'test', 'test', 'test', {
role: 'link'
}],
['test', 0.60, 0.62, 0.64, 'link'],
['test', 0.38, 0.53, 0.56, 'link'],
['test', 0.46800, 0.52100, 0.55500, 'link'],
['test', 0.43300, 0.49700, 0.53900, 'link']
]);
var options = {
title: 'test',
subtitle: 'test',
chartArea: {
width: '100%'
},
hAxis: {
title: 'test',
},
vAxis: {
title: 'test',
format: 'percent'
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
google.visualization.events.addListener(chart, 'select', function(e) {
var selection = chart.getSelection();
if (selection.length) {
var row = selection[0].row;
let link = data.getValue(row, 2);
window.open(link, '_blank');
}
});
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
</head>
<body>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
</body>
</html>

Related

Remove horizontal white line between Google stacked column charts

How do I remove the horizontal white lines between these stacked columns?
Here is my code:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Genre', 'One', 'Two'],
['2010', 10, 24],
['2020', 16, 22]
]);
var options = {
width: 300,
height: 200,
legend: 'none',
bar: { groupWidth: '100%' },
isStacked: true,
series: {
0: { color: '#40a1ec' },
1: { color: '#ff8888'}
},
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
I know how to remove the vertical white space between bars (using groupWidth), but I can't find a way to remove the horizontal white lines.
Thanks!
I think the only way is to add CSS style to columns so that stroke is not null:
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Genre', 'One', { role: 'style' }, 'Two', { role: 'style' } ],
['2010', 10, 'stroke-width: 1;stroke-color: blue;', 24,'stroke-width: 1;stroke-color: red;'],
['2020', 16, 'stroke-width: 1;stroke-color: blue;', 22, 'stroke-width: 1;stroke-color: red;']
]);
var options = {
width: 400,
height: 400,
legend: 'none',
bar: {
groupWidth: '100%'
},
isStacked: true,
series: {
0: {color: '#40a1ec'},
1: {color: '#ff8888'}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div">
</div>

1 Event Handler for 2 Google Charts

So, I have two Google bar charts displayed on the same page.I tried creating one event handler for both of them and passing in the chart and data into the selectHandler. Can someone tell me what I'm doing wrong?
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data1 = google.visualization.arrayToDataTable([
['Condition', 'Frequency'],
['Dementia', 6081],
['Hypertension', 6055],
['Hypercholesterolemia', 6035],
]);
var data2 = google.visualization.arrayToDataTable([
['Medication', 'Frequency'],
['Naproxen', 7632],
['Plavix', 7486]
]);
var options1 = {
title: 'Medical Conditions',
};
var options2 = {
title: 'Medications',
};
var conditionbarchart = new google.charts.Bar(
document.getElementById('conditions_chart'));
conditionbarchart.draw(data1, options1);
var medchart = new google.visualization.ColumnChart(
document.getElementById('medications_chart'));
medchart.draw(data2, options2);
google.visualization.events.addListener(conditionbarchart, 'select', selectHandler(conditionbarchart, data1));
google.visualization.events.addListener(medchart, 'select', selectHandler());
}
function selectHandler(mychart, mydata){
var selectedItem = mychart.getSelection()[0];
if(selectedItem){
var selection = mydata.getValue(selectedItem.row, 0);
alert('The user selected' + selection);
}
}
Here's the complete solution to answer my question:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.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();
data.addColumn('string', 'Condition');
data.addColumn('number', 'Frequency');
data.addRows([
['Dementia', 3],
['Hypertension', 1],
['Hypercholesterolemia', 1],
['Coronary artery disease', 1],
['Heaches', 2]
]);
// Create the data table.
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'Medication');
data2.addColumn('number', 'Frequency');
data2.addRows([
['Naproxen', 3],
['Plavix', 1],
['Lasix', 1],
['Insulin', 1],
['Neurontin', 2]
]);
// Set chart options
var options = {
bars: 'vertical', // Required for Material Bar Charts.
hAxis: {
slantedText:true,
slantedTextAngle:90
},
height: 400,
backgroundColor: {fill: 'transparent'},
legend: {position: 'none'},
colors: ['#1b9e77']
};
// Set chart options
var options2 = {
bars: 'vertical', // Required for Material Bar Charts.
hAxis: {
slantedText:true,
slantedTextAngle:90
},
height: 400,
backgroundColor: {fill: 'transparent'},
legend: {position: 'none'},
colors: ['#1b9e77']
};
// Instantiate and draw our chart, passing in some options.
var conditionsbarchart = new google.visualization.ColumnChart(document.getElementById('conditions_chart'));
var medchart = new google.visualization.ColumnChart(document.getElementById('medications_chart'));
function selectHandler(mychart, mydata) {
var selectedItem = mychart.getSelection()[0];
if (selectedItem) {
var topping = mydata.getValue(selectedItem.row, 0);
alert('The user selected ' + topping);
}
}
google.visualization.events.addListener(conditionsbarchart, 'select', function(){
selectHandler(conditionsbarchart, data);
});
conditionsbarchart.draw(data, options);
google.visualization.events.addListener(medchart, 'select', function(){
selectHandler(medchart, data2);
});
medchart.draw(data2, options2);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="conditions_chart" style="width:400; height:300"></div>
<div id="medications_chart" style="width: 400; height: 300"></div>
</body>
</html>

Hover on google chart acting weird on firefox

When adding a hover event to google chart svg element the results are different between firefox and chrome (chrome is doing what I would expect).
What I would like to achieve is the ability for the user to hover on a chart and not care how close he is to the line - the hover should be smooth and easy to use.
Here is the relevant plunker: https://plnkr.co/edit/2IF2BnX0tS2wznAUr5bs?p=preview
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<script>
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var dataTable = new google.visualization.DataTable({
cols: [
{ id: 'x', label: 'Num', type: 'number' },
{ id: 'y', label: 'Fn', type: 'number' }
]
});
for (var i = 0; i < 1000; i++) {
var xValue = { v: i };
var yValue = { v: i };
// add data row
dataTable.addRow([
xValue,
yValue
]);
}
var container = document.getElementById('chart_div');
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
dataTable: dataTable,
options: {
hAxis: {
gridlines: {
color: 'transparent'
},
title: 'Hover here is also fine'
},
tooltip: {
trigger: "none"
},
vAxis: {
gridlines: {
color: 'transparent'
},
title: 'Hover here is OK'
}
}
});
// add hover line
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
var svgParent = container.getElementsByTagName('svg')[0];
var layout = chart.getChart().getChartLayoutInterface();
var lineHeight = layout.getBoundingBox('chartarea').height - 18;
var lineTop = layout.getBoundingBox('chartarea').top;
var hoverLine = container.getElementsByTagName('rect')[0].cloneNode(true);
hoverLine.setAttribute('y', lineTop);
hoverLine.setAttribute('height', lineHeight);
hoverLine.setAttribute('width', '1');
hoverLine.setAttribute('stroke', 'none');
hoverLine.setAttribute('stroke-width', '0');
hoverLine.setAttribute('fill', '#cccccc');
hoverLine.setAttribute('x', 0);
svgParent.appendChild(hoverLine);
svgParent.addEventListener("mousemove", function (e) {
hoverLine.setAttribute('x', e.offsetX);
});
});
chart.draw(container);
}
</script>
<div id="chart_div"></div>
Hover on the chart with chrome to see the expected behaiour.
Hover on the chart with firefox to see the issue.
Any idea how to solve this? is this a google chart bug? Am I adding an event listener to the wrong element?
It seems that the children tags in your svg are capturing the mousemove events (which makes since due to event propogation).
Simply add a pointer-events:none to those children elements (I recommended to use an id for that svg element)
svg *{
pointer-events: none;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<script>
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var dataTable = new google.visualization.DataTable({
cols: [
{id: 'x', label: 'Num', type: 'number'},
{id: 'y', label: 'Fn', type: 'number'}
]
});
for (var i = 0; i < 1000; i++) {
var xValue = { v: i };
var yValue = { v: i };
// add data row
dataTable.addRow([
xValue,
yValue
]);
}
var container = document.getElementById('chart_div');
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
dataTable: dataTable,
options: {
hAxis: {
gridlines: {
color: 'transparent'
},
title: 'Hover here is also fine'
},
tooltip: {
trigger: "none"
},
vAxis: {
gridlines: {
color: 'transparent'
},
title: 'Hover here is OK'
}
}
});
// add hover line
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
var svgParent = container.getElementsByTagName('svg')[0];
var layout = chart.getChart().getChartLayoutInterface();
var lineHeight = layout.getBoundingBox('chartarea').height - 18;
var lineTop = layout.getBoundingBox('chartarea').top;
var hoverLine = container.getElementsByTagName('rect')[0].cloneNode(true);
hoverLine.setAttribute('y', lineTop);
hoverLine.setAttribute('height', lineHeight);
hoverLine.setAttribute('width', '1');
hoverLine.setAttribute('stroke', 'none');
hoverLine.setAttribute('stroke-width', '0');
hoverLine.setAttribute('fill', '#cccccc');
hoverLine.setAttribute('x', 0);
svgParent.appendChild(hoverLine);
svgParent.addEventListener("mousemove", function(e) {
hoverLine.setAttribute('x', e.offsetX);
});
});
chart.draw(container);
}
</script>
<div id="chart_div"></div>
</body>
</html>

Wrapping text of x-Axis Labels for Google Visualization Charts

I cannot seem to wrap my label for my column chart. I tried fiddling around with the options but it doesn't make any difference.
This is my current chart view, as you can see the label for column 2 has completely disappeared as the column 1 label has overlapped:
this is my Column Chart View:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1.1", { packages: ["bar"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Faculty Name', 'Book', 'Book Chapter', 'Journal Article', 'Conference'],
#Html.Raw(rows)]);
var options = {
title: '',
'width': 800,
'height': 500
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data1, options);
}
</script>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
You can reduce the font size down to 11 to get the label to show...
var options = {
'title': '',
'width': 800,
'height': 500,
'hAxis': {'textStyle': {'fontSize': 11}}
};
To do so, you will need to convert your options...
chart.draw(data1, google.charts.Bar.convertOptions(options));
you may draw a classical ColumnChart (when it is an option):
google.load("visualization", "1.1", {
packages: ["corechart"]
});
google.load("visualization", "1.1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Faculty Name', 'Book', 'Book Chapter', 'Journal Article', 'Conference'],
['Commerce, Law and Managment', 4, 9, 9, 1],
['foobar',2,2,2,3],
['Health Sciences', 0,2,3,1],
['Humanities', 0, 1, 1, 0],
['Science', 0, 0, 0, 1]
]);
var options = {
title: '',
'width': 800,
'height': 500,
vAxis: {
gridlines: {
count: 10
}
}
};
var chart = new google.visualization
.ColumnChart(document.getElementById('columnchart_material'));
chart.draw(data1, options);
}
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

Google Line chart from CSV

I am quite new to java-script and html stuff.. I am trying to make a basic line chart with Google chart using example.csv file but something is wrong. I dont see any chart. Nothing is being displayed. Please help. I came up with code after reading some similar codes
All i need is to start with this basic working code and develop into more advanced shape
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="jquery.csv-0.71.js"></script>
<script type="text/javascript">
//google.load('visualization', '1', {packages: ['corechart', 'line']});
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(BasicLine);
function BasicLine() {
// grab the CSV
$.get("example.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
var data = new google.visualization.arrayToDataTable(arrayData);
]);
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Temperature'
},
backgroundColor: '#f1f8e9'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
My CSV File is as below
Hour, Temperature
1, 70
2, 65
3, 60
4, 65
5, 67
6, 69
There is an syntax-error(the console should have told you about this).
Fixed version:
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(BasicLine);
function BasicLine() {
$.get("example.csv", function(csvString) {
var arrayData = $.csv.toArrays(csvString,
{onParseValue: $.csv.hooks.castToScalar}),
data = new google.visualization.arrayToDataTable(arrayData),
options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Temperature'
},
backgroundColor: '#f1f8e9'
},
chart = new google.visualization
.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
},
'text');
}
</script>

Categories