I have a google visualisation linechart. I am having issues formatting the labels on the h-axis. I would like to have them rounded off to integers so it looks neater. I have looked at the documentation but could not find a solution. Here is my code:
HTML
<div id="myChart2" name="myChart2" width="500" height="280"></div>
jQuery
$(document).ready(function(){
var chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'SPS');
chartData.addColumn('number', 'WGT');
var chartdatax = ["47", "47", "38", "35", "35"];
var chartdatay = ["1500", "2300", "2300", "1950", "1500"];
for (var i = 0; i < chartdatax.length; i++) {
chartData.addRow([parseFloat(chartdatax[i]), parseFloat(chartdatay[i])]);
};
options2 = {
height: 500,
hAxis: {
title: 'SPS',
gridlines: {
count: 15
}
},
vAxis: {
title: 'WGT',
gridlines: {
count: 15
}
},
chartArea: {
top: 40,
width: "70%",
height: "75%"
},
legend: {
position: 'none'
},
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('myChart2'));
myLineChart.draw(chartData, options2);
});
JSFiddle: https://jsfiddle.net/rdawkins/w83mdx3y/2/
You can add format:'#,###' to your hAxis object:
hAxis: {
format:'#,###',
title: 'SPS',
gridlines: {
count: 15
}
},
Here's an updated version of your fiddle: https://jsfiddle.net/w83mdx3y/3/
See customizing axes in the charts documentation for more information on how this works.
Related
I've been trying to add annotations to google bar chart. I've seen related questions about this, but can't solve it. There are 2 bar in charts and i want to show numbers on bars. I added 2 annotation column to my datatable. Chart draw works without annotations and there is no error at console. So i need some help. Here is my code:
var options = {
chart: {
title: 'xxxx',
subtitle: 'xxxx',
focusTarget:'category'
},
annotations: {
textStyle: {
color: 'black',
fontSize: 11,
},
alwaysOutside: true
},
height:300,
vAxis: {format: 'short'},
colors: ['#17807E', '#4285F4']
};
function drawAudits(Data) //data comes from another function with ajax call
{
var dataTbl = new google.visualization.DataTable();
dataTbl.addColumn('string', 'Months');
dataTbl.addColumn('number', 'Scheduled');
dataTbl.addColumn('number', 'Done');
dataTbl.addColumn({ type:'number' , role: 'annotation' });
dataTbl.addColumn({ type:'number' , role: 'annotation' });
for (var i = 0; i < Data.length; i++)
{
dataTbl.addRow([Data[i].month, Data[i].AllAudits, Data[i].DoneAudits, Data[i].AllAudits, Data[i].DoneAudits]);
} //last 2 column for annotations
var chart = new google.charts.Bar(document.getElementById('columnChartDiv'));
chart.draw(dataTbl,options);
}
thanks in advance.
annotations.* are not supported by Material charts, along with several other options...
see --> Tracking Issue for Material Chart Feature Parity #2143
the following option will style Core charts, similar to Material...
theme: 'material'
note: the annotation column should directly follow the series it represents...
see following working snippet...
google.charts.load('current', {
callback: function () {
var options = {
annotations: {
textStyle: {
color: 'black',
fontSize: 11,
},
alwaysOutside: true
},
chartArea: {
left: 36,
width: '100%'
},
colors: ['#17807E', '#4285F4'],
focusTarget:'category',
height:300,
legend: {
position: 'bottom'
},
theme: 'material',
title: 'xxxx',
vAxis: {
format: 'short',
viewWindow: {
max: 12
}
},
};
drawAudits();
window.addEventListener('resize', drawAudits, false);
function drawAudits(Data) {
var dataTbl = new google.visualization.DataTable();
dataTbl.addColumn('string', 'Months');
dataTbl.addColumn('number', 'Scheduled');
dataTbl.addColumn({ type:'number' , role: 'annotation' });
dataTbl.addColumn('number', 'Done');
dataTbl.addColumn({ type:'number' , role: 'annotation' });
Data = [
{month: 'Jan', AllAudits: 10, DoneAudits: 5},
{month: 'Feb', AllAudits: 10, DoneAudits: 6}
];
for (var i = 0; i < Data.length; i++) {
dataTbl.addRow([Data[i].month, Data[i].AllAudits, Data[i].AllAudits, Data[i].DoneAudits, Data[i].DoneAudits]);
}
var chart = new google.visualization.ColumnChart(document.getElementById('columnChartDiv'));
chart.draw(dataTbl,options);
}
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnChartDiv"></div>
I am using google charts and showing 3 tooltips by default when chart is loaded for that i have used
tooltip: { trigger: 'selection' },
aggregationTarget: 'none',
selectionMode: 'multiple'
Every thing is working fine but when the points get very close to each other like (1,1) and (1,1.5) the tool tips comes over each other please see this image. Is there any option or a way to overcome this.
google.charts.load('current', {
packages: ['corechart']
}).then(drawScatterChart);
function drawScatterChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'brand');
data.addColumn('number', 'store');
data.addColumn({
type: 'string',
role: 'tooltip'
});
data.addColumn({
type: 'string',
role: 'style'
});
var datarows = "";
var json = JSON.parse('[{"store":4.73977695167286,"brand":4.95353159851301,"empty":false,"tooltip":true,"tooltiptext":"Alpha Bravo"},{"store":0.362526138475839,"brand":0.835487337360595,"empty":false,"tooltip":true,"tooltiptext":"Avg. For Age"},{"store":0.598803222730479,"brand":1.14256989262171,"empty":false,"tooltip":true,"tooltiptext":"Franchisee Avg."},{"store":0.0929368029739777,"brand":0.288104089219331,"empty":false,"tooltip":true,"tooltiptext":"Andrew Richardson"},{"store":4.64684014869888,"brand":7.00743494423792,"empty":false,"tooltip":true,"tooltiptext":"April Singer"},{"store":4.64684014869888,"brand":7.00743494423792,"empty":false,"tooltip":true,"tooltiptext":"April Singer"}]');
$.each(json, function(ind, ele) {
//Every row given must be either null or an array.
var arr = [];
//'point {stroke-color: #A3A3A3; stroke-width: 0; fill-color: none;');/
if (ele.empty == true) {
arr.push(ele.brand, ele.store, "", 'point {stroke-color: #A3A3A3; stroke-width: 0; fill-color: none;'); //" Franchise Avg. ");fill-color: #a52714;
} else {
if (ele.tooltip == true) {
datarows += ind + ",";
}
arr.push(ele.brand, ele.store, ele.tooltiptext, 'point {stroke-color: #A3A3A3; stroke-width: 1'); //" Franchise Avg. ");fill-color: #a52714;
}
data.addRows([arr]);
});
var container = document.getElementById('chart_div');
var chart = new google.visualization.ScatterChart(container);
var options = {
width: 500,
height: 440,
legend: 'none',
hAxis: {
title: 'Brand Engagement',
gridlines: {
count: 11
}
}, //, minValue: 0
vAxis: {
title: 'Performance',
gridlines: {
count: 11
}
}, //, minValue: 0
backgroundColor: 'none',
colors: ['#fff'],
chartArea: {
left: 50,
top: 20,
width: "80%",
height: "87%"
},
tooltip: {
isHtml: true,
trigger: 'selection'
},
aggregationTarget: 'none',
pointSize: 5,
selectionMode: 'multiple',
};
google.visualization.events.addListener(chart, 'ready', setChartSelection);
function setChartSelection() {
var arrRows = datarows.split(",");
chart.setSelection([{
row: arrRows[0],
column: 1
},
{
row: arrRows[1],
column: 1
},
{
row: arrRows[2],
column: 1
}
]);
}
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chart_div" style="float: left;">
</div>
there are no options you can set to avoid overlap...
a possible solution would be to use the explorer option to pan and zoom
explorer: {
actions: ['dragToZoom', 'rightClickToReset']
}
see following working snippet, when the chart loads,
use the mouse to draw a square around the two points on the lower left,
once zoomed, both tooltips are displayed fully...
google.charts.load('current', {
packages: ['corechart']
}).then(drawScatterChart);
function drawScatterChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'brand');
data.addColumn('number', 'store');
data.addColumn({
type: 'string',
role: 'tooltip'
});
data.addColumn({
type: 'string',
role: 'style'
});
var datarows = "";
var json = JSON.parse('[{"store":4.73977695167286,"brand":4.95353159851301,"empty":false,"tooltip":true,"tooltiptext":"Alpha Bravo"},{"store":0.362526138475839,"brand":0.835487337360595,"empty":false,"tooltip":true,"tooltiptext":"Avg. For Age"},{"store":0.598803222730479,"brand":1.14256989262171,"empty":false,"tooltip":true,"tooltiptext":"Franchisee Avg."},{"store":0.0929368029739777,"brand":0.288104089219331,"empty":false,"tooltip":true,"tooltiptext":"Andrew Richardson"},{"store":4.64684014869888,"brand":7.00743494423792,"empty":false,"tooltip":true,"tooltiptext":"April Singer"},{"store":4.64684014869888,"brand":7.00743494423792,"empty":false,"tooltip":true,"tooltiptext":"April Singer"}]');
$.each(json, function(ind, ele) {
//Every row given must be either null or an array.
var arr = [];
//'point {stroke-color: #A3A3A3; stroke-width: 0; fill-color: none;');/
if (ele.empty == true) {
arr.push(ele.brand, ele.store, "", 'point {stroke-color: #A3A3A3; stroke-width: 0; fill-color: none;'); //" Franchise Avg. ");fill-color: #a52714;
} else {
if (ele.tooltip == true) {
datarows += ind + ",";
}
arr.push(ele.brand, ele.store, ele.tooltiptext, 'point {stroke-color: #A3A3A3; stroke-width: 1'); //" Franchise Avg. ");fill-color: #a52714;
}
data.addRows([arr]);
});
var container = document.getElementById('chart_div');
var chart = new google.visualization.ScatterChart(container);
var options = {
width: 500,
height: 440,
legend: 'none',
hAxis: {
title: 'Brand Engagement',
gridlines: {
count: 11
}
}, //, minValue: 0
vAxis: {
title: 'Performance',
gridlines: {
count: 11
}
}, //, minValue: 0
backgroundColor: 'none',
colors: ['#fff'],
chartArea: {
left: 50,
top: 20,
width: "80%",
height: "87%"
},
tooltip: {
isHtml: true,
trigger: 'selection'
},
aggregationTarget: 'none',
pointSize: 5,
selectionMode: 'multiple',
explorer: {
actions: ['dragToZoom', 'rightClickToReset']
}
};
google.visualization.events.addListener(chart, 'ready', setChartSelection);
function setChartSelection() {
var arrRows = datarows.split(",");
chart.setSelection([{
row: arrRows[0],
column: 1
},
{
row: arrRows[1],
column: 1
},
{
row: arrRows[2],
column: 1
}
]);
}
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chart_div" style="float: left;">
</div>
Im using the Canvasjs chart (http://canvasjs.com) I want to after the chart is render color of div border change to red
<div id="chartContainer" style="height:300px; width:90%; font-family:BMitra; text-align:center; border: 1px solid black;"></div>
<script>
function charting() {
var dataPo = [];
$.getJSON("<?=base_url();?>report/messages/create_report2", function(data) {
for( var i = 0; i < data.length; i++) {
dataPo.push({ label: data[i].label, y: data[i].y });
}
var chart = new CanvasJS.Chart("chartContainer", {
//backgroundColor: "#D2FEFF",
backgroundColor: "transparent",
theme: "theme3",
animationEnabled: true,
title:{
text:"my title",
fontFamily: "BYekan"
},
axisY:{
labelFontFamily: "BYekan"
},
axisX:{
labelFontFamily: "BYekan"
},
toolTip:{
fontSize: 19,
fontFamily: "BYekan",
},
data: [{
type: "column",
dataPoints : dataPo,
}]
});
chart.render();
}
</script>
First of all, your code is missing a few closed brackets.
Then, according to this docs, CanvasJS doesn't provide any callback handle for the render() function, but they say since it's very fast you probably won't have any issue in calling a function right after it.
This means you can change the border color with a jQuery call like this
$("yourDivSelector").css("border-color", "red");
and place it right after chart.render();. Your final code should look like this
<script>
function charting() {
var dataPo = [];
$.getJSON("<?=base_url();?>report/messages/create_report2", function(data) {
for( var i = 0; i < data.length; i++) {
dataPo.push({ label: data[i].label, y: data[i].y });
}
var chart = new CanvasJS.Chart("chartContainer", {
//backgroundColor: "#D2FEFF",
backgroundColor: "transparent",
theme: "theme3",
animationEnabled: true,
title:{
text:"my title",
fontFamily: "BYekan"
},
axisY:{
labelFontFamily: "BYekan"
},
axisX:{
labelFontFamily: "BYekan"
},
toolTip:{
fontSize: 19,
fontFamily: "BYekan",
},
data: [{
type: "column",
dataPoints : dataPo,
}]
});
chart.render();
$("yourDivSelector").css("border-color", "red");
});
}
</script>
I initially had a columnchart on page1 and a linechart on page2. They both display fine when on their own page. When I try combine the two on one page, they both display but they both are columncharts. I'm not sure what I am doing wrong. This is my code so far:
google.load('visualization', '1.0', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawchart);
function drawchart() {
var chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Arm');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < chartdatax.length; i++) {
chartData.addRow([parseFloat(chartdatax[i]),
parseFloat(chartdatay[i])]);
};
var options = {
height: 500,
hAxis: {
title: 'Arm C.G',
gridlines: {
count: 10
}
},
vAxis: {
title: 'Weight',
gridlines: {
count: 10
}
},
chartArea: {top:40, width: "70%", height: "75%"},
animation:{
duration: 1000,
easing: 'out',
startup: true,
},
legend: { position: 'none' },
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('chart1'));
myLineChart.draw(chartData, options);
}
function drawchart2(elevations, status) {
var chartDiv = document.getElementById('elevation_chart');
if (status !== google.maps.ElevationStatus.OK) {
// Show the error code inside the chartDiv.
chartDiv.innerHTML = 'Cannot show elevation: request failed because ' +
status;
return;
}
var chart = new google.visualization.ColumnChart(chartDiv);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation');
for (var i = 0; i < elevations.length; i++) {
data.addRow(['', elevations[i].elevation]);
}
chart.draw(data, {
height: 200,
legend: 'none',
titleY: 'Elevation (m)'
});
}
The code you have looks like it should work...
Would need to see where drawchart2 is called, the HTML elements, and any other code to be sure...
In this example, I add callback function drawcharts to start drawing...
google.load('visualization', '1.0', {'packages':['corechart'], 'callback': drawcharts});
function drawcharts() {
drawchart();
drawchart2();
}
function drawchart() {
var chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Arm');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < 10; i++) {
chartData.addRow([
parseFloat(i),
parseFloat(i * 1.5)
]);
};
var options = {
height: 500,
hAxis: {
title: 'Arm C.G',
gridlines: {
count: 10
}
},
vAxis: {
title: 'Weight',
gridlines: {
count: 10
}
},
chartArea: {top:40, width: "70%", height: "75%"},
animation:{
duration: 1000,
easing: 'out',
startup: true,
},
legend: {position: 'none'},
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('chart1'));
myLineChart.draw(chartData, options);
}
function drawchart2(elevations, status) {
var chartDiv = document.getElementById('elevation_chart');
var chart = new google.visualization.ColumnChart(chartDiv);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation');
for (var i = 0; i < 10; i++) {
data.addRow([
'',
i * 100
]);
}
chart.draw(data, {
height: 200,
legend: 'none',
titleY: 'Elevation (m)'
});
}
<script src="https://www.google.com/jsapi"></script>
<div id="chart1"></div>
<div id="elevation_chart"></div>
As said in the title, I'm trying to create a Javascript library from scratch which has to adjust the output of a chart created with Google Chart.
To explain better, Instead of doing this:
var options = {
title: 'Top Consuming Nations - Thousand barrels daily',
hAxis: {title: 'Year'},
width: 1050, height : 400,
vAxes: [
{title: 'Top Countries', titleTextStyle: {color: '#FF0000'}, maxValue: max}, // Left axis maxValue: 60000
{title: 'Total World', titleTextStyle: {color: '#FF0000'}, maxValue: tot} // Right
],
series:{
6: {targetAxisIndex: 1}
},
legend: { position: 'top', alignment: 'start' },
};
var chart = new google.visualization.LineChart(document.getElementById(chartDiv));
chart.draw(data, options);
I want to do something like this with a library created by me (skewedChart):
var options = {
title: 'Top Consuming Nations - Thousand barrels daily',
hAxis: {title: 'Year'},
width: 1050, height : 400,
vAxes: [
{title: 'Top Countries', titleTextStyle: {color: '#FF0000'}, maxValue: max}, // Left axis maxValue: 60000
{title: 'Total World', titleTextStyle: {color: '#FF0000'}, maxValue: tot} // Right
],
series:{
6: {targetAxisIndex: 1}
},
legend: { position: 'top', alignment: 'start' },
skew: 1
};
var chart = skewedChart.visualization.LineChart(document.getElementById(chartDiv));
chart.draw(data, options);
This is the code of my library, contained in the file skewedChart.js:
var skewedChart = {};
skewedChart.visualization = {};
skewedChart.visualization.LineChart = function(location) {
this.chart = new google.visualization.LineChart(location) ;
this.draw = function(data,option) {
option.height = this.skewHeight(option.width, option.skew) ;
option.vAxes[0].maxValue = this.skewMax(option.vAxes[0],option.skew) ;
this.chart.draw(data,option);
}
this.skewHeight= function(width,skewFactor) {
}
this.skewMax= function(series, skewFactor) {
}
};
The problem is that the chart returns "undefined", why? How can I do it better?
If you do not return anything from a function call it returns undefined which is what you are seeing. You need to add return this; at the end of your function.