Google charts X-axis don't look so good - javascript

I draw a chart using google charts API. and i get this chart:
My problem in this chart is the X-axis. The labels are not in look so good.
if I have more Strings in X-axis it's look like this:
I think the problem is because the X column type is string and not DATETIME.
How i change the column type in google charts?
Or How i change the X-axis without changin the column type?
I add the script here below...
PHP code:
$connection = mysql_connect('127.0.0.1','root','123456');
mysql_select_db('db_statmarket',$connection);
$result2 = mysql_query('select sum(`How much read from customer`) as Leads, Date from monitor group by Date;',$connection) or die('cannot show tables');
$json = array();
while($row = mysql_fetch_assoc($result2)) {
$json[] = $row;
}
$str='[\'Date\', \'Leads\'],';
foreach($json as $key=>$value){
$str = $str.'['.'\''.$value["Date"].'\''.', '.$value["Leads"].'],';
}
$str = substr($str, 0, -1);
$str = '['.$str.']';
$result1 = mysql_query('SELECT * FROM monitor ORDER BY customer_id DESC LIMIT 1;',$connection) or die('cannot show tables');
$row = mysql_fetch_assoc($result1);
JS code:
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $str?>);
var options = {
title: '',
curveType: 'function',
legend: { position: 'bottom' },
width: 1000,
backgroundColor: '#efeff0',
is3D: true,
chartArea: {
backgroundColor: {
stroke: '#efeff1',
strokeWidth: 1}},
height: 300
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
HTML code:
<div id="curve_chart" class="plot" style="width: 50% ; height: 400px ; float:left; margin-left:9%;"></div>
Thanks!

I found The answer.
I share It for all. so if somebody stuck, like me. will continue with this help quickly.
I create new variable: var showEvery = parseInt(data.getNumberOfRows() / 4);
And in the option attribute i add: hAxis: {showTextEvery: showEvery}
so the JS code seems like this:
var data = google.visualization.arrayToDataTable(<?php echo $str?>);
var showEvery = parseInt(data.getNumberOfRows() / 4);
var options = {
title: 'Title',
curveType: 'function',
legend: { position: 'bottom' },
width: 1000,
backgroundColor: '#efeff0',
is3D: true,
chartArea: {
backgroundColor: {
stroke: '#efeff1',
strokeWidth: 1}},
hAxis: {showTextEvery: showEvery},
height: 300
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);

You can force the x-axis of a BarChart setting the hAxis.viewWindow.min and hAxis.viewWindow.max:
hAxis: {
viewWindow: {
min: 0,
max: 100
},
ticks: [0, 50, 100] // display labels every 50
}
This will work for numbers or percentages, to use with dates is a bit more complex: checking Customizing Axes in Google API, there are two solutions:
You can change your major X axis to discrete and date type
The major axis of a chart can be either discrete or continuous. When using a discrete axis, the data points of each series are evenly spaced across the axis, according to their row index. When using a continuous axis, the data points are positioned according to their domain value.
Read, in the Customizing Axes link part which starts with Help! My chart has gone wonky! where explains the steps how to change from date to string and then customize it...

Related

Is there a way to reduce skew caused by few large y values in google line chart?

I am creating a line chart using google charts with the code below
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
const datat = new google.visualization.DataTable();
datat.addColumn("date", "Date");
datat.addColumn("number", "New Users");
datat.addColumn({'type': 'string', 'role': 'tooltip' , 'p': {'html': true}});
for(var i=0; i<data.length; i++){
datat.addRow([new Date(data[i]['year']), parseInt(data[i]['value']), "<div style='margin: 10px; font-size:1.1em;'>Date: " + data[i]['year'] + "<br>Users: " + parseInt(data[i]['value']) + "</div>"])
}
var options = {
title: 'New Users Graph',
curveType: 'function',
legend: { position: 'none' },
titleY: "Users",
titleX: "Date",
tooltip: {isHtml: true}
};
var chart = new google.visualization.LineChart(document.getElementById('users'));
chart.draw(datat, options);
}
Because the value range is high we can see the small values are very hardly visible. Is there a way to prevent such skew? The only option i have figured out is to increase the height of the div. I have set the height to 500px, still the graph has massive skew. We cannot even exclude the outlier or the high values. Is there a way to make the graph look little more balanced so that all values are easily visible? Thanks for the insights.

adding tooltips to google visualization bar chart

I'm trying to add custom tooltips to a Google Bar Chart, but I can't figure out how to do this.
Google provides a nice tutorial (at https://developers.google.com/chart/interactive/docs/customizing_tooltip_content), but it only discusses ColumnCharts, rather than Bar Charts.
Here's what my code looks like:
<div id="top_x_div" style="width: 900px; height: 500px;"></div>
google.load("visualization", "1.1",{packages:["bar"]});
google.setOnLoadCallback(drawStuff0);
function drawStuff0() {
var data = new google.visualization.arrayToDataTable([$data]);
var options = {
title: 'Categories',
width: 900,
legend: { position: 'none' },
chart: { title: 'popularity by number of queries',
subtitle: 'Number of times a category was queried' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Number of times a category was queried'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div0'));
// Convert the Classic options to Material options.
chart.draw(data, google.charts.Bar.convertOptions(options));
};
$data is simply a PHP variable containing the rows of the chart.
Could someone explain how to add a custom tooltip to this chart?
I've looked all over the web for a solution, I haven't been able to find one...
Add a new column to the DataTable object with the role tooltip :
data.addColumn({type: 'string', role: 'tooltip'});
Then loop through data and add whatever tooltip you want (example from the one column bar chart fiddle below) for each row :
for (var i=0; i<data.getNumberOfRows(); i++) {
data.setValue(i, 2, 'Tooltip #'+i);
}
demo -> http://jsfiddle.net/pc3zmb8w/
I cannot guide you more exactly since we dont know what your PHP $data is or how your chart looks like. But this is basically how you should do it, in all cases, when you want to add custom tooltips to a chart dynamically ...
Update - styling the tooltip
As for "is there a way to have the tool-tips appear as a rectangle, rather than a speech blurb", in the options - set tooltip as isHtml :
var options = {
tooltip: {isHtml: true}
}
Then the tooltip appears as a rectangle like normal HTML-element tooltips. You can also specify that you want to use HTML inside the tooltip itself :
data.addColumn({type: 'string', role: 'tooltip', p: {'html': true}});
For example to show the tooltip with the colors of a normal tooltip, but using a larger fontsize and a certain font :
div.tooltip {
background-color: #ffffca;
color: #000023;
padding: 10px;
font-size: 20px;
font-family : 'arial';
}
Set the tooltip as in original answer :
data.setValue(i, 2, '<div class="tooltip">Tooltip #'+i+'</div>');
demo -> http://jsfiddle.net/yhhhcj2f/

Organizing graph options in Google Charts

I'm creating a handful of pie charts using Google Charts. The majority of the graph options for the charts I'm creating are the same, except the titles. Is it possible to maintain a default set of options but write certain specific options for each graph (in this case, I just need to set a title).
Here's an example of the code I'm using:
var graphOptions = {
is3D: true,
pieSliceText: 'label',
colors: ['#F9B641', '#FBCB75', '#FCE1B0', '#FFF8EB', '#FFFFFF'],
backgroundColor: 'transparent',
titleTextStyle: {
color: '#FFF'
},
legend: {
textStyle: {
color: '#FFF'
}
},
chartArea: {
width: '90%',
height: '80%'
}
};
function pieChart1() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 216],
['Female', 238]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart1'));
chart.draw(data, graphOptions);
}
function pieChart2() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 116],
['Female', 98]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart2'));
chart.draw(data, graphOptions);
}
How would I go about setting the title option for each graph while still pulling the options from graphOptions?
As David explained, you can create an options object, and then edit properties of that object individually.
Here is a jsfiddle that shows it in action.
Note: you cannot see the titles because the BG and font color is white. Just do a ctrl+a to select everything and see them hidden there
Basically, you create a variable both functions can access (in your case graphOptions). In each function you set a new variable called options to equal graphOptions. You can then change the title property of the options variable to whatever you want without changing your default options template graphOptions, and use the options variable to draw the graph.
For your code, that means adding this code to each function:
var options = graphOptions;
options.title = "Pie Chart X"
You can change the title to whatever is appropriate, different for each graph. Then in the graph draw command, you change graphOptions to options to get
chart.draw(data, options);
Normally you'd do:
var options = { title: 'My Chat Title' };
In your case add title to your graphOptions object then do:
graphOptions.title = "The New Title";
for each graph.

Add Legend to Donut Chart - jqPlot

OK, this should be relatively simple :
I'm adding a donut chart, which does work
However, the 'legend' (like Head (+) along with the corresponding colour) does NOT show up.
Code :
$(document).ready(function(){
var s1 = [['Head (+)',<?php echo $headScore; ?>], ['Head (-)',<?php echo 6-$headScore; ?>]];
var s2 = [['Body (+)',<?php echo $totalScore-$headScore; ?>], ['Body (-)',<?php echo 7-$totalScore+$headScore; ?>]];
var plot3 = $.jqplot('linkchart', [s1,s2], {
title:"Score Profile",
seriesDefaults: {
// make this a donut chart.
renderer:$.jqplot.DonutRenderer,
rendererOptions:{
// Donut's can be cut into slices like pies.
sliceMargin: 3,
// Pies and donuts can start at any arbitrary angle.
startAngle: -90,
showDataLabels: false
},
legend: { show:true, location: 'e' }
}
});
});
What am I doing wrong?
Kameleon,
It looks like you have done a silly mistake. : )
First end the seriesDefaults property and then define the legend.
You have placed the legend inside the seriesDefaults.
var plot3 = $.jqplot('linkchart', [s1,s2], {
title:"Score Profile",
seriesDefaults: {
// make this a donut chart.
renderer:$.jqplot.DonutRenderer,
rendererOptions:{
// Donut's can be cut into slices like pies.
sliceMargin: 3,
// Pies and donuts can start at any arbitrary angle.
startAngle: -90,
showDataLabels: false
} // Not here...
},
//Place the legend here....
legend: { show:true, location: 'e' }
});
});
I have not tested it. But I think it should work.
Thank you.

Remove padding or margins from Google Charts

// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.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', 'Topping');
data.addColumn('number', 'Slices');
var myData = {
'Mushrooms': 3,
'Onions': 1,
'Olives': 1,
'Zucchini': 1,
'Pepperoni': 2
};
var rows = [];
for (element in myData) {
rows.push([element + " (" + myData[element] + ")", myData[element]])
}
data.addRows(rows);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':450,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
Example fiddle
How do I remove padding or margins in this example?
By adding and tuning some configuration options listed in the API documentation, you can create a lot of different styles. For instance, here is a version that removes most of the extra blank space by setting the chartArea.width to 100% and chartArea.height to 80% and moving the legend.position to bottom:
// Set chart options
var options = {'title': 'How Much Pizza I Ate Last Night',
'width': 350,
'height': 400,
'chartArea': {'width': '100%', 'height': '80%'},
'legend': {'position': 'bottom'}
};
If you want to tune it more, try changing these values or using other properties from the link above.
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
I arrived here like most people with this same issue, and left shocked that none of the answer even remotely worked.
For anyone interested, here is the actual solution:
... //rest of options
width: '100%',
height: '350',
chartArea:{
left:5,
top: 20,
width: '100%',
height: '350',
}
... //rest of options
The key here has nothing to do with the "left" or "top" values. But rather that the:
Dimensions of both the chart and chart-area are SET and set to the SAME VALUE
As an amendment to my answer. The above will indeed solve the "excessive" padding/margin/whitespace problem. However, if you wish to include axes labels and/or a legend you will need to reduce the height & width of the chart area so something slightly below the outer width/height. This will "tell" the chart API that there is sufficient room to display these properties. Otherwise it will happily exclude them.
It's missing in the docs (I'm using version 43), but you can actually use the right and bottom property of the chart area:
var options = {
chartArea:{
left:10,
right:10, // !!! works !!!
bottom:20, // !!! works !!!
top:20,
width:"100%",
height:"100%"
}
};
So it's possible to use full responsive width & height and prevent any axis labels or legends from being cropped.
There's a theme available specifically for this
options: {
theme: 'maximized'
}
from the Google chart docs:
Currently only one theme is available:
'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:
chartArea: {width: '100%', height: '100%'},
legend: {position: 'in'},
titlePosition: 'in', axisTitlesPosition: 'in',
hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}
There is this possibility like Aman Virk mentioned:
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
But keep in mind that the padding and margin aren't there to bother you.
If you have the possibility to switch between different types of charts like a ColumnChart and the one with vertical columns then you need some margin for displaying the labels of those lines.
If you take away that margin then you will end up showing only a part of the labels or no labels at all.
So if you just have one chart type then you can change the margin and padding like Arman said. But if it's possible to switch don't change them.

Categories

Resources