I am show graphs from Google Charts, using a horizontal column chart. I want to remove the blank space above and below the graph.
Here is the code called (some info removed due to NDA):
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[null, "...","...","...","...","...","...","...","...","Total Average"],
[null, 100,100,100,100,100,88.89,100,100,98.70]
]);
var options = {
height: 540,
title: 'Title here',
vAxis: { textPosition: 'none', viewWindowMode: 'maximized' },
colors:["#0B0842","#ADAEAE","#BE3351","#498101","#0D80CA","#A3C116","#91A96B","#E8F72B","#424242"],
hAxis: { textPosition: 'none', minValue: 0, maxValue: 100 },
chartArea: { left: 0, width: "78%" },
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
The space above and below the bars is normally there to separate bar groups when you have multiple rows of data. If you don't want that space, then you can set the bar.groupWidth option in your chart to a larger percentage (up to 100%; default is the golden ratio, roughly 61.8%):
var options = {
height: 540,
title: 'Title here',
vAxis: { textPosition: 'none', viewWindowMode: 'maximized' },
colors:["#0B0842","#ADAEAE","#BE3351","#498101","#0D80CA","#A3C116","#91A96B","#E8F72B","#424242"],
hAxis: { textPosition: 'none', minValue: 0, maxValue: 100 },
chartArea: { left: 0, width: "78%" },
bar: {groupWidth: '100%'}
};
Try this, it worked for me:
var chart_height = data.getNumberOfRows() * 40;
var options = {
chartArea: {
top: 0,
left: '30%',
width: '70%',
bottom: 0
},
height: chart_height
};
Related
I am trying to add chart data from PHP file.
Chart is drawn when I add the values manually - data: [28,20,2,7],
But chart doesn't appear, when I add the data from PHP file.
Where am I going wrong here?
How can I add these values from PHP output?
My PHP code:
echo json_encode(array($rectotals,$recX,$recXS,$recXM));
Php file output (this looks OK):
[28,20,2,7]
Here is how i get the data:
$.getJSON("chartdata.php").then(function(chart_data1){
alert(chart_data1);
})
Alert result (This is also OK):
localhost:63342 says 28,20,2,7
My chartjs script:
<canvas id="myChart" width="400" height="340"></canvas>
<script>
$.getJSON("chartdata.php").then(function(chart_data){
alert(chart_data);
})
//setTimeout(function() { alert(db_data1); }, 2000);
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Total', 'Size X', 'Size XS', 'Size SM],
datasets: [{
data: chart_data,
backgroundColor: [
'rgba(54, 162, 235, 1)',
'rgb(255,99,132)',
'rgba(255, 159, 64, 1)',
'rgb(255,206,86)'
],
borderColor: [
'rgba(54, 162, 235, 1)',
'rgba(255, 99, 132, 1)',
'rgb(255,159,64)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 0.5,
}]
},
options: {
responsive: true,
animation: {
duration: 2800,
easing: 'easeInOutQuad',
},
layout: {
padding: {
left: 0,
right: 0,
top: 15,
bottom: 0
}
},
cutoutPercentage : 75,
legend: {
display: false,
position: 'bottom',
fullWidth: true,
}
}
});
</script>
var ctx = document.getElementById("myChart").getContext("2d");
let myChart = null;
function getConfig(chart_data){
return ({
type: "pie",
data: {
labels: ["Total", "Size X", "Size XS", "Size SM"],
datasets: [
{
data: chart_data,
backgroundColor: [
"rgb(54,162,235)",
"rgb(255,99,132)",
"rgba(255, 159, 64, 1)",
"rgb(255,192,33)"
],
borderColor: [
"rgb(255,255,255)",
"rgb(255,255,255)",
"rgb(255,255,255)",
"rgb(255,255,255)"
],
hoverBackgroundColor: ['#373739', '#373739', '#373739', '#373739'],
}
]
},
options: {
responsive: true,
animation: {
duration: 0, //2800, I remove animation time
easing: "easeInOutQuad"
},
tooltips: {
mode: 'nearest'
},
layout: {
padding: {
left: 0,
right: 0,
top: 15,
bottom: 0
}
},
cutoutPercentage: 66,
legend: {
display: false,
position: "bottom",
fullWidth: true
}
}
});
}
function getJSON(){
// emulate fetch
return new Promise(resolve => {
const chart_data = [
Math.random() * 50,
Math.random() * 50,
Math.random() * 50,
Math.random() * 50
];
resolve(chart_data)
})
}
function update(){
getJSON().then(data => {
myChart.data.datasets[0].data = data;
myChart.update();
});
}
function initializeChart() {
getJSON().then(data => {
myChart = new Chart(ctx, getConfig(data));
});
}
initializeChart();
document.getElementById('update_chart').addEventListener('click', update, false);
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div>
<button id="update_chart">Update Records</button>
</div>
<canvas id="myChart" width="50" height="40"></canvas>
</body>
</html>
Query.getJSON() makes an asynchronous HTTP request. Once the result arrives, the chart has already been created and the obtained data has no effect on the chart.
To solve this, place the chart creation inside the then callback as follows.
$.getJSON("chartdata.php").then(function(chart_data) {
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'pie',
...
});
How to avoid the negative values from google chart, I tried viewWindow: { min: 0,} in my Y axis, but still it showing negative values only.
please help some one please. Thanks in advance
<div class="timeline-item">
<div id="top_x_div" style="width: 100%; height: 300px;"></div>
</div>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawStacked);
function drawStacked() {
var data = new google.visualization.arrayToDataTable([
['Courses', 'Students'],
["Electronics", 2 ],
]);
var options = {
legend: { position: 'none' },
isStacked: true,
colors: ['green'],
bars: 'vertical', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'bottom', label: 'Percentage'} // Top x-axis.
}
},
axes: {
y: {
0: { side: 'bottom', label: 'Students'}, // Top x-axis.
/* viewWindow: {
min: 0,
},*/
}
},
vAxis: {
viewWindow: {
min: 0
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
};
</script>
You need to set the viewWindow on the vAxis option.
vAxis: {
viewWindow: {
min: 0
}
}
Source
I'm working on a dual Y-axis linechart that is to have both height and weight on the Y-axes with the date displaying on the X-axis:
I'm pulling the data from my MYSQL database and encoding it into json and the passing it to my function that draws the chart as shown:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Height');
data.addColumn('number', 'Weight');
data.addRows([
<?php
$chart_info = $db->prepare("SELECT `height`, `weight`, `date_captured` FROM `child_results_capture` ");
$chart_info->execute();
$result = $chart_info->fetchAll(PDO::FETCH_ASSOC);
$chart_data = '';
foreach($result as $value)
{
$chart_data.="['".$value['date_captured']."',".$value['height'].",".$value['weight']."],";
// var_dump($chart_data);exit;
// echo $chart_data;
}
echo $chart_data;
?>
]);
var options = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
0: {axis: 'Height'},
1: {axis: 'Weight'}
},
axes: {
y: {
Height: {label: 'Height (cm)'},
Weight: {label: 'Weight (kg)'}
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('graph_chart'));
chart.draw(data, options);
}
</script>
<div id="graph_chart"></div>
The Json returned from my php bit looks like this:
['2016-07-27',51,3.4],['2016-08-03',52,4],['2016-08-10',53,5],['2016-08-17',54,6],['2016-08-24',55,7],['2016-08-31',56,8],
And my output looks like this:
As shown above, I only get one Y-axis(for the height) and my chart axes are not labelled with the corresponding names
Will appreciate being pointed in the right direction
the specific configuration options used in the question to build the Dual-Y Chart
are for Material charts only --> google.charts.Line
var optionsMatl = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
0: {axis: 'Height'},
1: {axis: 'Weight'}
},
axes: {
y: {
Height: {label: 'Height (cm)'},
Weight: {label: 'Weight (kg)'}
}
}
};
a different set of options is needed to build a Dual-Y Chart
in a Classic chart --> google.visualization.LineChart
var optionsCore = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
1: {
targetAxisIndex: 1
}
},
vAxes: {
0: {
title: 'Height (cm)'
},
1: {
title: 'Weight (kg)'
}
},
theme: 'material'
};
from the documentation for Dual-Y Charts...
In the Material code ..., the axes and series options together specify the dual-Y appearance of the chart. The series option specifies which axis to use for each. The axes option then makes this chart a dual-Y chart.
In the Classic code, this differs slightly. Rather than the axes option, you will use the vAxes option (or hAxes on horizontally oriented charts). Also, instead of using names, you will use the index numbers to coordinate a series with an axis using the targetAxisIndex option.
see following working snippet, which draw both...
google.charts.load('current', {packages:['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Height');
data.addColumn('number', 'Weight')
data.addRows([
['2016-07-27',51,3.4],
['2016-08-03',52,4],
['2016-08-10',53,5],
['2016-08-17',54,6],
['2016-08-24',55,7],
['2016-08-31',56,8]
]);
var optionsMatl = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
0: {axis: 'Height'},
1: {axis: 'Weight'}
},
axes: {
y: {
Height: {label: 'Height (cm)'},
Weight: {label: 'Weight (kg)'}
}
}
};
var chartMatl = new google.charts.Line(document.getElementById('chart_div_matl'));
chartMatl.draw(data, google.charts.Line.convertOptions(optionsMatl));
var optionsCore = {
title: 'Height-Weight graph',
width: 900,
height: 500,
legend: {
position: 'top',
alignment: 'end'
},
series: {
1: {
targetAxisIndex: 1
}
},
vAxes: {
0: {
title: 'Height (cm)',
},
1: {
title: 'Weight (kg)'
}
},
theme: 'material'
};
var chartCore = new google.visualization.LineChart(document.getElementById('chart_div_core'));
chartCore.draw(data, optionsCore);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>Material Chart</div>
<div id="chart_div_matl"></div>
<div>Core Chart</div>
<div id="chart_div_core"></div>
I have been trying for three hours now with the Google Charts API to change the color of the next that I have displayed below. As you can see I've gotten the X/Y axis drawing in White, but That's about all I could do albeit changing the background color.
I've been reading the documentation located here: https://developers.google.com/chart/interactive/docs/gallery/table
Many labels in the chart have associated textStyle options. In your case, you want to use hAxis.textStyle, vAxis.textStyle, legend.textStyle, and titleTextStyle:
hAxis: {
textStyle: {
color: '#ffffff'
}
},
vAxis: {
textStyle: {
color: '#ffffff'
}
},
legend: {
textStyle: {
color: '#ffffff'
}
},
titleTextStyle: {
color: '#ffffff'
}
legend.textStyle and tooltip.textStyle control this as documented for scatter charts for instance here
I think, I have understood the main properties of Google Charts. Here they are:
// options
var options = {
// title
title: 'What is your favourite season?',
titleTextStyle: {color: '#006633'},
// horizontal axis
hAxis: {
textStyle: {
color: '#ffffff',
fontName: 'Tahoma',
fontSize: 12},
slantedText: false,
minTextSpacing: 1,
},
// vertical axis
vAxis: {
textStyle: {
color: '#ffffff',
fontName: 'Tahoma',
fontSize: 12},
slantedText: false,
minTextSpacing: 1,
},
// legend
legend: {
textStyle: {
color: '#c7d781',
fontSize:14,
bold:true,
italic:false
}
},
// tooltip
tooltip: {
textStyle: {
color: '#ff0000',
fontSize:14,
bold:true,
italic:false
}
},
// chart
width:740,
height:200,
backgroundColor: 'transparent',
baselineColor: 'white'
};
var chart = new google.visualization.ColumnChart(document.getElementById('chartContainer-03'));
chart.draw(data, options);
}
Source code and demo here
I am creating google barchart, that takes data from database.The problem is that data contains values below "1" like 0.6,0.7 etc
It wont appear on graph. Graph only shows values starting from 1.
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'annotation',
sourceColumn: 1,
calc: 'stringify'
}]);
var options = {
width: 395,
height: 200,
title: 'Values',
'chartArea': {right: 37,width:'40%'},
titleTextStyle: {
fontName: 'Arial',
fontSize: 14
},
legend: {position: 'none'},
colors:['#4A9218'],
};
var chart = new google.visualization.BarChart(document.getElementById('ch7'));
chart.draw(view, options);
}
</script>
<div id="ch7" style="width:33%; height:200px"></div>
If your values are all positive you can use logarithmic scale setting option hAxis.logScale to true. Othervise you can set also minimum value to be shown. Options are set like:
hAxis: {
logScale: true
}
or like
hAxis: {
minValue: 0
}