I'm using google Bar Charts https://developers.google.com/chart/interactive/docs/gallery/barchart. The titles for are stored in a database and some them contain apostrophes. Those apostrophes in the title are rendered as &39, for example "he's" ---> "he&39s"
I want apostrophes to be rendered normally.
I've found several solutions but none of them worked so far for such a simple task.
Any working solution?
update:
This is rendered properly, as I'm goooood
var chart = new google.visualization.ColumnChart(document.getElementById("my_div"));
chart.draw(data, {
title: "I'm goooood",
legend: {position: "none"},
});
But this - not, it's ---> I'm goooood
var chart = new google.visualization.ColumnChart(document.getElementById("my_div"));
chart.draw(data, {
title: "<%= get_value_from_db() %>",
legend: {position: "none"},
});"
On other pages, without charts but text only, the "<%= get_value_from_db() %>" gets rendered correctly -- I'm goooood.
I've had the same issue but only with ' and " which get rendered as "&39," or "&34," .
As none of the above fixes worked for me, a quick and pretty dirty solution I've relied upon is using string.replace with the prime ( ′ ), and double prime ( ″ ) symbols - looped through a reasonable number of times.
<%= varName.replace("\'",'′').replace("\"",'″ ') %>
Also I think this error may have something to do with how Google Charts and EJS interact together as both the OP and I are using it and have this issue. (pure speculation)
Use \ to escape '. Look at the example
<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([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company\'Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
},
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
</head>
<body>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>
</body>
</html>
As you are getting tittle from db, you have to add \ before ' in title string using string manipulation.
you can use a dom element to convert the ascii characters to readable text
function convertToText(ascii) {
var tempDiv = document.createElement('DIV');
tempDiv.innerHTML = ascii;
return tempDiv.textContent || tempDiv.innerText || '';
}
in your options...
chart.draw(data, {
title: convertToText("<%= get_value_from_db() %>"),
legend: {position: "none"},
});
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['x', 'y'],
['A', 9],
['B', 30],
['C', 50],
['D', 70],
['E', 90]
]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {
title: convertToText('I'm goooood'),
legend: {position: 'none'},
});
function convertToText(ascii) {
var tempDiv = document.createElement('DIV');
tempDiv.innerHTML = ascii;
return tempDiv.textContent || tempDiv.innerText || '';
}
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Just use decodeURI on the text.
My title comes from what the user has chosen from categories.
So, when I show the chart title, I do like this:
title: decodeURI(strCategory) + ' from ' + decodeURI(strInitialDate) + ' to ' + decodeURI(strEndDate)
My categories include, 'Alimentação', 'Feira/Sacolão' and others...
It works even on smartphones.
Added: Works with alerts also...
alert('Sem dados para o período de: ' + decodeURI(strInitialDate) + ' a ' + decodeURI(strEndDate))
Related
I am currently attempting to design a Google Chart which is modelled based on values within certain div tags throughout a html document.
as it stands, there are a number of tags throughout the document such as:
<div id="abc"> 11000 </div>
<div id="def"> 12500 </div>
<div id="ghi"> 17000 </div>
I would like the Google Chart to reference these values as the Y-axis.
The Google Charts code works fine like this:
<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([
['Age', 'Current', 'Proposed'],
['25', 10000],
['35', 15170],
['45', 21660],
]);
var options = {
title: 'Balance Comparison',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
I would like to change the array in such a way that references the div values. I attempted to do this, and ended up with this:
function drawChart() {
var y1 = document.getElementByID("abc")
var y2 = document.getElementByID("def")
var y3 = document.getElementByID("ghi")
var data = google.visualization.arrayToDataTable([
['Age', 'Current'],
['25', y1],
['35', y2],
['45', y3],
]);
This does not seem to work however, and I am at a loss as to how to get it working.
it will work, first, a couple things...
javascript is case sensitive, change getElementByID to getElementById (note the last letter)
getElementById gets the element, but you want the contents of the element.
use innerHTML to get the contents.
var y1 = document.getElementById('abc').innerHTML;
finally, google charts expects a number for the y value,
innerHTML returns a string.
use parseFloat to convert the string to a number.
parseFloat(y1)
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var y1 = document.getElementById('abc').innerHTML;
var y2 = document.getElementById('def').innerHTML;
var y3 = document.getElementById('ghi').innerHTML;
var data = google.visualization.arrayToDataTable([
['Age', 'Current'],
['25', parseFloat(y1)],
['35', parseFloat(y2)],
['45', parseFloat(y3)],
]);
var options = {
title: 'Balance Comparison',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="abc"> 11000 </div>
<div id="def"> 12500 </div>
<div id="ghi"> 17000 </div>
<div id="curve_chart"></div>
I'd like to diplay my array in google stacked column chart. I generated the array looks like this.
array(n) { ["5pm"]=> int(4) ["6pm"]=> int(0),... } //Monday
array(n) { ["5pm"]=> int(5) ["6pm"]=> int(1),... } //Tuesday
...
array(n) { ["5pm"]=> int(4) ["6pm"]=> int(2),... } //Sunday
The number of entries in array needs to vary (depends on entries in database, but is the same for all days).
The JS from google charts needs to look like this
var data = google.visualization.arrayToDataTable([
['Hours', '5pm', '6pm',...],
['Mon', 4, 0],
['Tue', 5, 1],
...
['Sun', 4, 2]
]);
Thanks for the help ;)
Heer is a sample code where I'm getting data from PHP & passing that to JavaScript for plotting the chart. One thing needs to check that all rows should have an equal number of elements.
So, according to your question, all "Time Periods" rows should have an equal number of elements else, it'll not work.
<?php
$chartData = array(
array('Year', 'Sales', 'Expenses', 'Profit'),
array('2014', 1000, 400, 200),
array('2015', 1170, 460, 250),
array('2016', 660, 1120, 300),
array('2017', 1030, 540, 350)
);
$chartDataInJson = json_encode($chartData);
?>
<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(<?php echo $chartDataInJson; ?>);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
</head>
<body>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
</body>
</html>
Hope it'll clear all of your doubt.
I have this chart which is a bar chart showing multiple data. The data is divided by year (2014, 2015) and quarter (Q1,Q2,Q3,Q4). I can show either the quarters on the x-axis or the year, but not both. I made a screenshot and put the years in there to show what I'd like to achieve.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<body>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['bar']});
google.setOnLoadCallback(drawBasic);
function drawBasic() {
//create data table object
var data = google.visualization.arrayToDataTable([
['','Sales', 'Expenses'],
['Q1',1000, 400],
['Q2',1000, 400],
['Q3',1170, 460],
['Q4',900, 500],
['Q1',1400, 420],
['Q2',1240, 750],
['Q3',1001, 360],
['Q4',788, 800]
]);
var options = {
width: 800, height: 600, is3D: false, title: 'Company Earnings'
};
var chart = new google.charts.Bar(
document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
<div id="chart_div"></div>
</body>
</html>
Here is the result (I added the years in paint):
Any ideas how to do this?
I remembered seeing the following post sometime back that lets you add multiple x-axis details. Perhaps this will help:
http://www.lornajane.net/posts/2011/adding-multiple-axis-labels-to-a-google-chart
I'm new with jquery.
I have a html and jquery that plots a line chart from a csv. I would like to write a text in a textbox and append it to my chart.
Any help is appreciated :)
<div class="optionGroup"><label for="chart_title">Title</label><input type="text" name="chart_title" value="" id="chart_title"></div>
var chart = new google.visualization.LineChart(document.getElementById('chart'));
//this is my attempt
var titlus = +$('#chart_title').keyup(function(){
var value = $( this ).val();
$( 'chart' ).text( value );
})
var options = {
title: titlus,//<--it should go here
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
chart.draw(view, options);
You need to render the graph in the beginning, if you want to change the graph title in real time you should draw the graph again when a key is pressed. In order to do this a callback function for load must be added because the rendering/API is asynchronous. As a recommendation, it is a not a good practice rendering the graph any time a key is pressed, it is better to create a button to submit the title or detecting when the return key is pressed. This is a working example of what you asked:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
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 = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
document.getElementById("chart_title").onkeyup = function() {
options.title = this.value;
chart.draw(data, options);
}
}
</script>
</head>
<body>
<div>
Title: <input type="text" name="chart_title" value="" id="chart_title">
</div>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
I am using following code to plot column chart using google visualization API.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages: ["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Expenses'],
['2004', 400],
['2005', 460],
['2006', 1120],
['2007', 540]
]);
var options = {
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
When I click on one of bar it is displaying data of x and y axis in tooltip. I want data which is displayed in tooltip(2006 and 460) as alert. How to find it.
Use a "select" event handler, and grab the data from the DataTable based on the selected element:
google.visaulization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
if (selection.length) {
alert(data.getValue(selection[0].row, 0) + ' ' + data.getValue(selection[0].row, selection[0].column));
}
});