How to show the complete number on the Y-axis in Google Chart? - google-visualization

I am using Google Chart to display a bar chart. Please see the screen shot below. Problem is, the highest number on the y-axis is always getting chopped off. In the screenshot, the highest number is supposed to be 55; but, as you can see, only the lower portion of 55 is showing. I have tried changing the height of my div and changing the height of the chart. They didn't solve the problem. I have also tried changing the max value of the y-axis but that does not solve the problem in the sense that the highest number would get chopped off (for example, for the chart in my screen shot, if I were to change the max value to 60, it is true that 55 would show completely but 60 would be chopped off).
How can I show the complete number on the highest value on y-axis in Google Charts?
google.charts.load('current', {packages: ['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.arrayToDataTable([
["", ""],
["Col_1", <?php echo $col1Count; ?>],
["Col_2", <?php echo $col2Count; ?>],
["Col_3", <?php echo $col3Count; ?>],
["Col_4", <?php echo $col4Count; ?>]
]);
var options = {
width: 720,
height: 550,
legend: { position: 'none' },
vAxis: {
viewWindow: {
min: 5,
max: 55
},
ticks: [5,10,15,20,25,30,35,40,45,50,55]
}
};
// Instantiate and draw the chart.
var chart = new google.charts.Bar(document.getElementById('myChart'));
chart.draw(data, google.charts.Bar.convertOptions(options));
google.visualization.events.addListener(chart, 'ready', function () {
html2canvas(document.getElementById('myChart')).then(function(canvas) {
// console.log(canvas.toDataURL('image/png'));
//document.getElementById('myChart').appendChild(canvas);
jQuery.ajax({
type: 'POST',
url: 'https://myURL.com/saveimage.php',
data: {
// send image string as data
imgstr: canvas.toDataURL('image/png')
},
success: function(response) {
alert(response);
}
});
});
});
}

The material Bar chart has far fewer options than the classic charts. I suspect that if you add a title, even if it is just a space character, that will reserve enough space above the chart to show the topmost axis tick label without truncation.

Related

Howto show absolute number in Apexcharts pie chart

The pie chart I created with Apexcharts shows relative (percentage) numbers at the circle (like the "99.9%" in the screenshot below).
Instead of the relative number I'd like to show the absolute value like what's in the tooltip (see example: "6752").
I tried a formatter function with signature function(value, {seriesIndex,dataPointIndex,w}), but value is the relative value (e.g. 99.9), dataPointIndex is undefined, seriesIndex is always 1 and w contains the whole chart config without being specific to this slice of the pie.
How can I show absolute numbers?
You have the right strategy, but probably not the right formatter. The one you need is dataLabels.formatter:
let options = {
series: [10, 20, 15],
chart: {
width: 350,
type: 'pie'
},
labels: ['Label 1', 'Label 2', 'Label 3'],
dataLabels: {
formatter: (val, { seriesIndex, w }) => w.config.series[seriesIndex] // <--- HERE
}
};
let chart = new ApexCharts(document.querySelector('#chart'), options);
chart.render();
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div id="chart"></div>

How do I move the x axis like a window in google chart while x increases

I would like to draw a chart to my html, the chart I am using is google chart. However, while my x value is increasing, the chart is getting bigger. But I just want a fixed size window which increase both minimum x value and maximum x value. Like sliding window.
The attachment below is my code. This is the js code which updates the gets the value and updates the chart
// load google charts library
google.load("visualization", "1", {packages:["corechart"]});
// for rest, walk, fast_walk data
var data, options, chart;
var xMin = 0;
var xMax = 10;
var i = 0;
/* initialize chart1 - rest, walk, fast_walk data */
function drawChart(data, options) {
var chart = new
google.visualization.LineChart(document.getElementById('data-container'));
chart.draw(data, options);
return(chart);
}
/* update the chart1 - rest, walk, fast_walk data */
function updateChart(percentage) {
i = (i + 1);
data.addRow([
""+i,
percentage
]);
if(xMax >= 9) {
xMin + 1;
}
xMax + 1;
chart.draw(data, options);
}
$(function() {
data = google.visualization.arrayToDataTable([
['Time', 'percentage'],
['0', 0],
]);
options = {
title: 'Energy data',
"curveType": "function",
vAxis: {
min: xMin,
max: xMax
}
};
chart = drawChart(data, options);
});
/* reset charts */
function reset(){
i = 0;
data = google.visualization.arrayToDataTable([
['Time', 'percentage'],
['0', 0],
]);
options = {
title: 'Energy data',
"curveType": "function",
hAxis: {
viewWindow: {
min: 0,
max: 10
}
}
};
chart = drawChart(data, options);
}
I am wondering if it can be designed into a sliding window, so that the x value doesn't stick with the minimum value 0. instead if we want to see the earliest value, we can just scroll left.
According to the documentation at [https://developers.google.com/chart/interactive/docs/gallery/linechart]
/* copied from site*/
var options = {
chart: {
title: 'Box Office Earnings in First Two Weeks of Opening',
subtitle: 'in millions of dollars (USD)'
},
width: 900, //<--- set fixed width like so
height: 500
};
To get a scrollable div,you can wrap your chart inside another div
<div class='h-scrollable' > <!---- chart code here ----> </div>
and for css
.h-scrollable {
width: 100%;
overflow: hidden; // only if you don't want y axis to be scrollable
overflow-x: auto;
}
Now, for the chart give a width depending on the number of x values you have. You could do a mathematical computation by taking the width of the h-scrollbale div in javascript and dividing it by number of x-points you want in a window and then multiplying it with total x values you have and setting it as chart width.
Update:
inititally get the width of h-scrollable as let viewWidth = document.querySelector(".h-scrollable").offsetWidth
[refer : How to find the width of a div using raw JavaScript?
Then if you want to show 10 x values in a view, divide viewWidth by 10 to get one xWidth. Now you can re-render the chart each time by setting width as no.of X values * xWidth so that it scrolls accordingly
Upon each update, you can just remove the first raw.

Google Visualization X Axis is overlapped

I am drawing Charts Using google.visualization API .
The User can select a value from DropDown in Front End and clicks on Go , it fetches data from backend .
Sometimes the data that fetched is more and sometimes less
When the Data is more , the x-axis being overlapped
Please see this fiddle
http://jsfiddle.net/7wYP2/462/
This is my code
google.load('visualization', '1', {packages: ['corechart']});
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([["strike_pr","CE","PE"],["5500",1875,2025],["6000",61500,104775],["6100",450,13725],["6500",35400,421800],["6600",150,121950],["6700",600,770925],["6800",13650,370425],["6900",33375,586650],["7000",744375,1122075],["7100",229200,355875],["7200",199800,689850],["7300",461550,244425],["7400",442950,439125],["7500",835350,484725],["7600",459000,82800],["7700",482250,48000],["7800",893250,11550],["7900",1215600,13500],["8000",741150,93525],["8100",242325,6150],["8200",326175,1500],["8300",365850,75],["8500",104850,2925],["9000",13050,11775]]);
var options = {
title:"OPTION INDEX distribution",
width: 800,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
is3D:true,
"vAxis":{"title":"Open Interest"},
"hAxis":{"title":"Strike Price"},
};
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data, options);
}
google.setOnLoadCallback(drawVisualization);
Could you please let me know how to resolve this issue ??

Google Chart: Showing bars wrongly

I am currently working on Google Bar Chart-Dual-X and it is working nice.
Issue:
The bar is showing wrongly.For an example: Suppose I want to show Obtained Marks and Total Marks.But Issue is Google Chart shows Obtained Marks Bar bigger than the Total Mark(which is not true at all). You can see below pic :
As you can see in the pic that Chap 6,7,8 is having Obtained Mark Bar is bigger than the Total Mark Bar.
Code
<script type="text/javascript">
google.load("visualization", "1.1", {packages:["bar"]});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Subject', 'Obtained Marks', 'Total Marks'],
<?php
$i=1;
foreach($sql_get_marks_results as $sql_get_marks_result){
echo "['".$sql_get_marks_result->meta_subject."', ".$sql_get_marks_result->obtained_marks.", ".$sql_get_marks_result->total_marks."]";
if($i != count($sql_get_marks_results)){echo ",";}
$i++;
}
?>
]);
var options = {
width: 900,
chart: {
title: 'Markesheet',
subtitle: 'distance on the left, brightness on the right'
},
bars: 'horizontal', // Required for Material Bar Charts.
series: {
0: { axis: 'obtained' }, // Bind series 0 to an axis named 'distance'.
1: { axis: 'total' } // Bind series 1 to an axis named 'brightness'.
},
axes: {
x: {
obtained: {label: 'Obtained'}, // Bottom x-axis.
total: {side: 'top', label: 'Total'} // Top x-axis.
}
}
};
var chart = new google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
};
</script>
Is anyone here who came across similar problem or anyone can help me out in this ?
Tell me if you want more detail about this.
The display shown in your screen shots is correct.
The "total marks" (red) dataset follows the bottom x-axis.
And the "Obtained" (blue) dataset follows the top x-axis.
I think that the scale (inferred by your data range) of your two X-axis is quite close. And because of this it's easy to confuse them.
Dual x-axis charts are good for complementary datasets with values in very different ranges as in the example given in the documentation.
In your case you'd be better of using a simple (single axis) bar chart to avoid that kind of confusion.

How to show an Empty Google Chart when there is no data?

Consider drawing a column chart and I don't get any data from the data source, How do we draw an empty chart instead of showing up a red colored default message saying "Table has no columns"?
What I do is initialize my chart with 1 column and 1 data point (set to 0). Then whenever data gets added I check if there is only 1 column and that it is the dummy column, then I remove it. I also hide the legend to begin so that it doesn't appear with the dummy column, then I add it when the new column gets added.
Here is some sample code you can plug in to the Google Visualization Playground that does what I am talking about. You should see the empty chart for 2 seconds, then data will get added and the columns will appear.
var data, options, chart;
function drawVisualization() {
data = google.visualization.arrayToDataTable([
['Time', 'dummy'],
['', 0],
]);
options = {
title:"My Chart",
width:600, height:400,
hAxis: {title: "Time"},
legend : {position: 'none'}
};
// Create and draw the visualization.
chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
chart.draw(data,options);
setTimeout('addData("12:00",10)',2000);
setTimeout('addData("12:10",20)',3000);
}
function addData(x,y) {
if(data.getColumnLabel(1) == 'dummy') {
data.addColumn('number', 'Your Values', 'col_id');
data.removeColumn(1);
options.legend = {position: 'right'};
}
data.addRow([x,y]);
chart.draw(data,options);
}​
A even better solution for this problem might be to use a annotation column instead of a data column as shown below. With this solution you do not need to use any setTimeout or custom function to remove or hide your column. Give it a try by pasting the given code below into Google Code Playground.
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['', { role: 'annotation' }],
['', '']
]);
var ac = new google.visualization.ColumnChart(document.getElementById('visualization'));
ac.draw(data, {
title : 'Just a title...',
width: 600,
height: 400
});
}
​
The way I did this was by disabling the pie slices, turning off tooltips, stuffing in a pretend value and making it gray. I'm sure there are more clever ways to do this, but this worked for me where the other methods didn't.
The only drawback is that it sets both items in the legend to gray as well. I think you could perhaps just add a third item, and make it invisible on the legend only. I liked this way though.
function drawChart() {
// Define the chart to be drawn.
data = new google.visualization.DataTable();
data.addColumn({type: 'string', label: 'Result'});
data.addColumn({type: 'number', label: 'Count'});
data.addRows([
['Value A', 0],
['Value B', 0]
]);
var opt_pieslicetext = null;
var opt_tooltip_trigger = null;
var opt_color = null;
if (data.getValue(1,1) == 0 && data.getValue(0,1) == 0) {
opt_pieslicetext='none';
opt_tooltip_trigger='none'
data.setCell(1,1,.1);
opt_color= ['#D3D3D3'];
}
chart = new google.visualization.PieChart(document.getElementById('mydiv'));
chart.draw(data, {sliceVisibilityThreshold:0, pieSliceText: opt_pieslicetext, tooltip: { trigger: opt_tooltip_trigger }, colors: opt_color } );
}