Google Charts -- Axis Values overlapping and how to avoid - charts

How do I avoid this axis overlap in google charts? I am working with a large data set and not sure what to do to solve this issue. I am using a large number of dates for the x axis. The options I use for my chart are
var options = {
tooltip: {
trigger: 'both',
},
width: 1900,
height: 400,
vAxis: { 'title': 'Volume' },
crosshair: { trigger: 'both'}
};
EDIT::
PHP creation of the containers
if( isset($db_graph_query)){
while($row = mysqli_fetch_array($db_graph_query)) {
$rowcount2++;
// removed the hard coded column set and made it driven off of the array below
// could have pulled it from the $cols array above, but there might be columns that we don't wish to show
echo " <tr>";
$colindex = 0;
foreach( $cols as $column_name ) {
$style = "";
$val = $row[$column_name];
if ( isset($column_callback)) {
$style=$column_callback($colindex, $val);
}
if ($colindex == 0) {
echo "<td style='text-align: left; width: 1pt;'><a href='#' class='toggle' onClick='drawChart(\"$val\");'>$val</a></td>";
$tempval = $val;
} else {
echo "<td $style>$val</td>";
}
$colindex++;
}
echo "</tr>";
echo "<tr class='tablesorter-childRow'>";
echo "<td colspan='12'>";
echo "<div id='$tempval' style='height: 400px;'></div>";
echo "</td>";
echo "</tr>";
}
}
EDIT::
Draw Chart Script, creates the chart options, grabs data from SQL DB and adds into the data:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
function drawChart(inputname) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'RunDate');
data.addColumn('number', 'Runs');
data.addColumn('number', 'Fails');
data.addRows([
<?php
$dbName = "mydb";
$config = parse_ini_file("configfile.ini",true);
$dbUser = $config["DB"]["db_user"];
$dbServer = $config["DB"]["db_ip"];
$dbPassword = $config["DB"]["db_pass"];
$con = mysql_connect($dbServer, $dbUser, $dbPassword);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbName, $con);
$sql = mysql_query("SELECT * From MyTestTable");
$output = array();
while($row = mysql_fetch_array($sql)) {
// create a temp array to hold the data
$temp = array();
// add the data
$temp[] = '"' . $row['Name'] . '"';
$temp[] = '"' . $row['RunDate'] . '"';
$temp[] = (int) $row['Runs'];
$temp[] = (int) $row['FailCount'];
// implode the temp array into a comma-separated list and add to the output array
$output[] = '[' . implode(', ', $temp) . ']';
}
// implode the output into a comma-newline separated list and echo
echo implode(",\n", $output);
mysql_close($con);
?>
]);
var view = new google.visualization.DataView(data);
view.setRows(data.getFilteredRows([
{column: 0, value: inputname}
]));
view.setColumns([1,2,3]);
var options = {
tooltip: {
trigger: 'both',
},
vAxis: { 'title': 'Volume' },
crosshair: { trigger: 'both'},
width: 1900,
height: 400
};
var chart = new google.visualization.LineChart(document.getElementById(inputname));
chart.draw(view, options);
}
</script>

try using option for slanted text...
hAxis: {slantedText: true}

The horizontal axis ticks should not be overlapping at all, and I believe the only way this could be happening is if your chart is not visible at the time you draw it, in which case the chart thinks the ticks don't take up any space and can be packed in as dense as possible. Slanting or alternating would not necessarily help until you get down to the minimum spacing constraint.
So the only real solution, at this time, is to make sure your chart is visible when you draw it.

Related

overlayMaps and markers in Leaflet

I am using Leaflet to show two sets of markers on a map. Let's call them "trip 1" and "trip 2".
The markers information (lat, lon, description, etc.) is stored in two separate geojson files.
I would like to show each trip separately, using two L.layerGroup, one for each trip.
The code below is the page I have written: so far this is what I have.
The problem is that all markers are already shown on the map before selecting each trip (top right corner - see attached image).
I would like the markers to be shown after selection.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
<div id="map" class="embed-container"></div>
</center>
<script>
var viaggio1 = L.layerGroup([
<?php
$url = 'docs/guardini.geojson'; // path to your JSON file
$dati = file_get_contents($url); // put the contents of the file into a variable
$result = json_decode($dati, true); // decode the JSON feed
$data = $result['features'];
foreach($data as $key => $row) {
$numero = $row['id'];
$nome = $row['name'];
$lat = $row['lat'];
$lon = $row['lon'];
$text = $row['text'];
$pic = $row['pic'];
$link = $row['link'];
?>
L.marker(['<?=$lat;?>', '<?=$lon;?>']),
<?php
}
?>
]);
</script>
<script>
var viaggio2 = L.layerGroup([
<?php
$url2 = 'docs/guardini2.geojson'; // path to your JSON file
$dati2 = file_get_contents($url2); // put the contents of the file into a variable
$result2 = json_decode($dati2, true); // decode the JSON feed
$data2 = $result2['features'];
foreach($data2 as $key2 => $row2) {
$numero2 = $row2['id'];
$nome2 = $row2['name'];
$lat2 = $row2['lat'];
$lon2 = $row2['lon'];
$text2 = $row2['text'];
$pic2 = $row2['pic'];
$link2 = $row2['link'];
?>
L.marker(['<?=$lat2;?>', '<?=$lon2;?>']),
<?php
}
?>
]);
</script>
<script>
var overlayMaps = {
"viaggio 1": viaggio1,
"viaggio 2": viaggio2
};
var map = L.map('map').setView([48.3585, 10.86135], 6);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: '© OpenStreetMap',
maxZoom: 19,
minZoom: 4
}).addTo(map);
L.control.scale({imperial: false}).addTo(map);
var pol = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: '© OpenStreetMap',
minZoom: 4,
maxZoom: 19
}).addTo(map);
var sat = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
{
attribution: 'Tiles © Esri — Source: Esri, IGN, IGP, UPR-EGP, and the GIS User Community',
minZoom: 4,
maxZoom: 19
});
var arte = L.tileLayer('http://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.{ext}',
{
attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
subdomains: 'abcd',
minZoom: 4,
maxZoom: 19,
ext: 'png'
});
var baseMaps = {
"politica": pol,
"satellitare": sat,
"artistica": arte
};
//L.control.layers(baseMaps).addTo(map);
L.control.layers(baseMaps, overlayMaps).addTo(map);
var stile = {
"color": "#ff3385",
"weight": 4,
"opacity": 0.65
};
</script>
<?php
$url = 'docs/guardini.geojson'; // path to your JSON file
$dati = file_get_contents($url); // put the contents of the file into a variable
$result = json_decode($dati, true); // decode the JSON feed
$data = $result['features'];
foreach($data as $key => $row) {
$numero = $row['id'];
$nome = $row['name'];
$lat = $row['lat'];
$lon = $row['lon'];
$text = $row['text'];
$pic = $row['pic'];
$link = $row['link'];
?>
<div id="sidebar<?=$numero;?>" align="left"></div>
<script>
var sidebar<?=$numero;?> = L.control.sidebar('sidebar<?=$numero;?>', {
closeButton: true,
position: 'left'
});
sidebar<?=$numero;?>.setContent('<br>luogo nr. <?=$numero;?><br><br><b><?=$nome;?></b><br><br><?=$text;?><br><br><img src="<?=$pic;?>"><br><br><?=$link;?><br>');
map.addControl(sidebar<?=$numero;?>);
setTimeout(function () {
sidebar<?=$numero;?>.hide();
}, 700);
var marker<?=$numero;?> = L.marker(['<?=$lat;?>', '<?=$lon;?>']).addTo(map).on('click', function () {
sidebar<?=$numero;?>.toggle();
});
</script>
<?php
}
?>
<?php
$url2 = 'docs/guardini2.geojson'; // path to your JSON file
$dati2 = file_get_contents($url2); // put the contents of the file into a variable
$result2 = json_decode($dati2, true); // decode the JSON feed
$data2 = $result2['features'];
foreach($data2 as $key2 => $row2) {
$numero2 = $row2['id'];
$nome2 = $row2['name'];
$lat2 = $row2['lat'];
$lon2 = $row2['lon'];
$text2 = $row2['text'];
$pic2 = $row2['pic'];
$link2 = $row2['link'];
?>
<div id="sidebar<?=$numero2;?>" align="left"></div>
<script>
var sidebar<?=$numero2;?> = L.control.sidebar('sidebar<?=$numero2;?>', {
closeButton: true,
position: 'left'
});
sidebar<?=$numero2;?>.setContent('<br>luogo nr. <?=$numero2;?><br><br><b><?=$nome2;?></b><br><br><?=$text2;?><br><br><img src="<?=$pic2;?>"><br><br><?=$link2;?><br>');
map.addControl(sidebar<?=$numero2;?>);
setTimeout(function () {
sidebar<?=$numero2;?>.hide();
}, 700);
var markerr<?=$numero2;?> = L.marker(['<?=$lat2;?>', '<?=$lon2;?>']).addTo(map).on('click', function () {
sidebar<?=$numero2;?>.toggle();
});
</script>
<?php
}
?>
</div>
</div>
</body>
</html>
It looks like you are adding the markers to the map:
L.marker(['<?=$lat2;?>', '<?=$lon2;?>']).addTo(map)
And I think what you want to do is add the markers to the layerGroups:
L.marker(['<?=$lat2;?>', '<?=$lon2;?>']).addTo(viaggio2)

OOCharts monthly timeline

I'm using Oocharts.com's API and I'm doing a 12 month timeline chart, but it displays a daily data point for each day instead of combining them into a monthly amount. So, instead of displaying 1 visit per day, I want it to show 30 visits for the month. How can I do that?
Here's a link to their documentation, I read the entire thing and don't see how to do this. I even changed my date range from 1y to 12m and it didn't do anything.
http://docs.oocharts.com/
I solved this by using an oocharts query + google's visualization API. Here's my code for displaying filtered results for the last 12 months:
// What's our months?
$months = array();
for ($i = -12; $i < 0; $i++)
{
$month_time = strtotime($i . ' months');
$months[] = date('F Y', $month_time);
}
// Add js code to get unique page views for last year on a timeline chart
$oocharts_js .= '
oo.load(function(){
var query = new oo.Query("' . $this->config->item('oocharts_profile_id') . '", "13m");
query.addMetric("ga:uniquePageviews");
query.addDimension("ga:nthMonth");
query.setFilter("' . $oochart_filter . '");
query.setIndex(2);
query.execute(function(data){
console.log(data.rows);
google.load("visualization", "1", {packages:["corechart"]});
var dataTable = google.visualization.arrayToDataTable([
["Month", "Page Visits"],
';
foreach ($months as $key => $value)
{
$oocharts_js .= '["' . $value . '", data.rows[' . $key . '][1]],';
}
$oocharts_js .= '
]);
var options = {
chartArea: {top: 10, left: 30, height: "60%"},
hAxis: {
slantedText: true,
},
vAxis: {
viewWindow:{
min:0,
},
},
pointSize: 5,
lineWidth: 3,
};
var chart = new google.visualization.LineChart(document.getElementById("chart_' . $business->business_id . '"));
chart.draw(dataTable, options);
});
});
';

How put dates on flot

I've a little problem, I need to do a curve with on y axis numbers and x axis dates.. but I can't display some dates...
My code :
<script type="text/javascript">
$(function () {
<?php
echo " var data = [";
$cpt="0";
include ('../connect.php');
// Requete SQL
$req = 'select "SPP_NB_IND" from "STAT_PERPHY" where "SPP_SAGES" = \''.$sages.'\' AND "SPP_DATE" between \''.$jourtableau.' 00:00:00\' and \''.$jourfinw.' 23:59:59\'';
$res = pg_query($req);
$reqd = 'select "SPP_DATE" from "STAT_PERPHY" where "SPP_SAGES" = \''.$sages.'\' AND "SPP_DATE" between \''.$jourtableau.' 00:00:00\' and \''.$jourfinw.' 23:59:59\' AND "SPP_NB_IND" IS NOT NULL ';
$resd = pg_query($reqd);
// On met les valeurs obtenues dans un tableau
while ( $row = pg_fetch_assoc ($res) )
{
//echo $row['SPP_NB_IND']."<br>";
$var=$row['SPP_NB_IND'];
while ( $roww = pg_fetch_assoc ($resd) )
{
$abscisse=date('d-m', strtotime($roww['SPP_DATE']));
}
echo "[$abscisse, $var],";
$cpt++;
}
echo "];";
?>
var options = {
lines: {
show: true
},
points: { show: true
},
xaxis: {
mode: "time",
timeformat : "%d/%m"
}
};
<?php
echo "$.plot($(\"#graph1\"), [ data ], options);";
?>
});
</script>
[/CODE]
When I put $abscisse, my curve is vertical and if I put $cpt, I have a "normal" curve... but I want to see dates corresponding with numbers..
Freindly,
Tanaes.
See the documentation:
You have to give flot timestamps, not already formated dates. For PHP use something like
$abscisse = strtotime($roww['SPP_DATE']) * 1000;

highcharts, json data: line and column

May be really basic question:
I'm playing with highcharts with two series, one represented with line and other with column, data is loaded using json, the problem is in how to tell highcharts one serie should be represented with line and the other with column type, like this
The problem (for me) comes when Series options in json mode of highcharts are only like this:
},
series: json
});
whilst in "normal mode" you can set for example:
series: [{
**type: 'column',**
name: 'Name',
data: [],
},{
type: 'spline',
name: 'Max Pax',
data: [],
draggableY: true,
dragMinY: 0,
dragMaxY: 200,
.......
Am I missing something?
php code that retrives data from db:
$con = mysql_connect("localhost", "*******","*******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wordpress_8", $con);
$sth = mysql_query("SELECT * FROM wp_maxpax_A where fecha='12/11/2013' ");
$rows = array();
$rows['name'] = 'MaxPax';
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['a1300'];
$rows['data'][] = $r['a1315'];
$rows['data'][] = $r['a1330'];
$rows['data'][] = $r['a1345'];
}
$sth = mysql_query("SELECT overhead FROM projections_sample");
$rows1 = array();
$rows1['name'] = 'Overhead';
while($rr = mysql_fetch_assoc($sth)) {
$rows1['data'][] = $rr['overhead'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
print json_encode($result, JSON_NUMERIC_CHECK);
Output looks like:
[{"name":"MaxPax","data":[40,19,40,21]},{"name":"Overhead","data": [21990,22365,21987,22369,22558,22987,23521,23003,22756,23112,22987,22897]}]
You need to define this parameter in JSON, or parse your json after receive, and set this paraemter, then use in Highcharts.
EDIT:
You can replace this lines
$sth = mysql_query("SELECT * FROM wp_maxpax_A where fecha='12/11/2013' ");
$rows = array();
$rows['name'] = 'MaxPax';
with
$sth = mysql_query("SELECT * FROM wp_maxpax_A where fecha='12/11/2013' ");
$rows = array();
$rows['name'] = 'MaxPax';
$rows['type'] = 'line';
Similar in next series.
Second solution is push type after getting json like:
$getJSON('path/to/json',function(data){
data[0].type='column';
data[1].type='line';
var options = {
// your options
series: data
};
$('#container').highcharts(options);
});

google chart api date format

The below answer suggested works using mysql_ however I have decided to switch to PDO for the increased security if offers. However When I apply the same code, I am struggling to get it to work.I had to switch the while to foreach for PDO.
UPDATE: Using PHP PDO
$sql = "SELECT * FROM userrecords";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row)
{
$dateArray = explode('-', $row['eventdate']);
$year = $dateArray[0];
$month= $dateArray[1] - 1;
$day= $dateArray[2];
$dataArray[] = "[new Date ($year, $month, $day), {$row['scientificname']}, {$row['category_of_taxom']}]";
}
echo $dataArray;
Building on the solution from your other question, you have to parse your dates into javascript's Date object format:
$dataArray = array();
while($row = mysqli_fetch_array($result)) {
$dateArray = explode('-', $row['Date']);
$year = $dateArray[0];
$month = $dateArray[1] - 1; // subtract 1 since javascript months are zero-indexed
$day = $dateArray[2];
$dataArray[] = "[new Date($year, $month, $day), {$row['SpeciesA']}, {$row['Speciesb']}]";
}
Because the json_encode function will break the dates here, we have to parse it into the DataTable constructor a bit differently:
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Species A');
data.addColumn('number', 'Species B');
data.addRows(<?php echo '[' . implode(',', $dataArray) . ']'; ?>);