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;
Related
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)
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.
I would like to ask how to add the customized line into chart by using jpgraph. For example, to identify SUNDAY on date which selecting from database, the jpgraph will draw a straight line with red color on each Sunday which will be showed on x-axis.
Does anyone meet the related issue and has been solved? Please tell me, thank you.
The code of my situation:
`
$dateLocale = new DateLocale();
$dateLocale->Set('');
$file_date = date("Ymd");
$dateArray = array();
$dataSuccessful = array(); //get from db
$dataUser_not_found = array();
$dataAcc_not_activated = array();
$dataUnsuccess_others = array();
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "example";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$dateArray[] = date("d/m/Y (D)", strtotime($row["date"]));
$dataSuccessful[] = $row["login_success_count"];
$dataUser_not_found[] = $row["unsuccess_not_found"];
$dataAcc_not_activated[] = $row["unsuccess_not_activated"];
$dataUnsuccess_others[] = $row["unsuccess_others"];
}
} else {
echo "No results in this table";
}
function strBefore($string, $substring) {
$pos = strpos($string, $substring);
if($pos === false){
return $string;
}else{
return(substr($string, 0, $pos));
}
}
function strAfter($string, $substring) {
$pos = strpos($string, $substring);
if($pos === false){
return $string;
}else{
return(substr($string, $pos+strlen($substring)));
}
}
JpgraphError::SetImageFlag(false);
JpGraphError::SetLogFile('syslog');
// Create the graph.
$graph = new Graph(2560, 1320);
//initialization of the default theme
$graph->ClearTheme();
//$graph->SetScale('datlin',0,$x_max);
$graph->SetScale('datlin');
$graph->img->SetMargin(60,150,50,60);
$graph->SetShadow();
// Create the linear plot (SUCCESSFUL)
$l1plot=new LinePlot($dataSuccessful);
$l1plot->SetColor('lightblue:0.4');
$l1plot->SetFillColor("lightblue:0.7");
$l1plot->SetWeight(2);
$l1plot->SetLegend('The total number of visit (SUCCESSFUL)');
// Create the linear plot (UNSUCCESSFUL)
$user_not_found_plot = new LinePlot($dataUser_not_found);
$user_not_found_plot->SetColor('orange:1.2');
$user_not_found_plot->SetFillColor('orange#0.2');
$user_not_found_plot->SetLegend('(UNSUCCESSFUL) User not found');
$acc_not_activated_plot = new LinePlot($dataAcc_not_activated);
$acc_not_activated_plot->SetColor('green:0.8');
$acc_not_activated_plot->SetFillColor('green#0.4');
$acc_not_activated_plot->SetLegend('(UNSUCCESSFUL) Account not activated');
$others_plot = new LinePlot($dataUnsuccess_others);
$others_plot->SetColor('lightred:1.2');
$others_plot->SetFillColor('lightred#0.4');
$others_plot->SetLegend('(UNSUCCESSFUL) Others');
$graph->title->Set('log report');
$graph->xaxis->title->Set('Last 30 days');
$graph->title->SetFont(FF_FONT1,FS_BOLD);
$graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD);
$graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
$graph->setYScale(0, 'lin', 0, 2000);
/* Add the plots to the graph */
//SUCCESSFUL numbers
$graph->Add($l1plot);
//UNSUCCESSFUL numbers
$graph->AddY(0,$user_not_found_plot);
$graph->AddY(0,$acc_not_activated_plot);
$graph->AddY(0,$others_plot);
$graph->ynaxis[0]->SetColor('red');
$graph->ynaxis[0]->title->Set('The number of visit (UNSUCCESSFUL)');
$graph->ynaxis[0]->scale->SetGrace(80);
//As demo, set the specific date on x-axis
$graph->xaxis->SetLabelFormatString('d/m/Y',true);
$graph->xaxis->setTickLabels($dateArray);
// Display the graph
// Get the handler to prevent the library from sending the image to the browser
$gdImgHandler = $graph->Stroke(_IMG_HANDLER);
// Default is PNG so use ".png" as suffix
$fileName = "pic/oul207_log_".$file_date.".png";
$graph->img->Stream($fileName);
?>`
I guess you don't want a tick, so here's how to add a red vertical line:
require_once ('jpgraph/jpgraph_plotline.php');
$v_plot = new PlotLine();
$v_plot->SetDirection(VERTICAL);
$v_plot->SetColor('red');
$v_plot->SetPosition(2);
$graph->AddLine($v_plot);
Of course you'd need to calculate your sunday(s) relative to the x-axis and set the position(s) accordingly.
I have used the jQuery UI Autocomplete demo source code for the Categories example (http://jqueryui.com/autocomplete/#categories) and have it working (querying a database which returns a JSON array).
I'm building a search function for an art gallery and my categories are Artists and Exhibitions. I want to show results from one or both categories. My problem is that results are only showing when the search term covers a result in both categories.
My suggestions script uses the search term to query two different database tables. I format and append the results into a single JSON array with rows for ["id"], ["value"], ["label"] and ["category"].
So for the search term CORN, the results that come back might be:
{ label: "Christopher Corner", category: "Artists" },
{ label: "New Pictures From Cornwall", category: "Exhibitions" },
{ label: "Cornie Collins", category: "Artists" },
At the moment when I type a search term, the possible results are only shown as long as a result is possible in ALL my categories, rather than what I want, which is one or more. So when I type CORN, I can see an Artist named Corner, and an Exhibition about Cornwall, but the minute I type the E of CORNE, all the options disappear, including the Artist whose name is Corner (which I would expect to remain).
I'm new to jQuery and jQuery UI and struggling to understand where the logic would be to select a list item from any category rather than all of them.
I have edited to add my code. This is the backend suggestions file - search_suggestions.php:
<?php
# if the 'term' variable is not sent with the request, exit
if (!isset($_REQUEST['term'])) {
exit;
}
# retrieve the search term that autocomplete sends
$term = trim(strip_tags($_GET['term']));
$a_json = array();
$a_json_row = array();
# connect to database, send relevant query and retrieve recordset
include 'includes/db_access.php';
$compoundFind = $fm->newCompoundFindCommand('web_Artists');
$request1 = $fm->newFindRequest('web_Artists');
$request2 = $fm->newFindRequest('web_Artists');
$request1->addFindCriterion('Last name', '*'.$term.'*');
$request2->addFindCriterion('First name', '*'.$term.'*');
$compoundFind->add(1, $request1);
$compoundFind->add(2, $request2);
$compoundFind->addSortRule('Last name', 1, FILEMAKER_SORT_ASCEND);
$result = $compoundFind->execute();
if (FileMaker::isError($result)) {
die();
}
$records = $result->getRecords();
# loop through records compiling JSON array
foreach ($records as $record) {
$artistID = htmlentities(stripslashes($record->getRecordID())) ;
$artistName = htmlentities(stripslashes($record->getField('Full name'))) ;
$a_json_row["id"] = $artistID;
$a_json_row["value"] = $artistName;
$a_json_row["label"] = $artistName;
$a_json_row["category"] = "Artists";
array_push($a_json, $a_json_row);
}
$findCommand = $fm->newFindCommand('web_Exhibitions');
$findCommand->addFindCriterion('Title', '*'.$term.'*');
$result = $findCommand->execute();
if (FileMaker::isError($result)) {
die();
}
$records = $result->getRecords();
foreach ($records as $record) {
$exhibitionID = htmlentities(stripslashes($record->getField('Exhibition ID'))) ;
$exhibitionTitle = htmlentities(stripslashes($record->getField('Title'))) ;
$a_json_row["id"] = $exhibitionID;
$a_json_row["value"] = $exhibitionTitle;
$a_json_row["label"] = $exhibitionTitle;
$a_json_row["category"] = "Exhibitions";
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
flush();
?>
And here is the JS in my section which sets things up:
<style>
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
</style>
<script>
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
},
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item) {
var li;
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
li = that._renderItemData( ul, item );
if ( item.category ) {
li.attr( "aria-label", item.category + " : " + item.label );
}
});
}
});
</script>
<script>
$(function() {
$( "#searchInput" ).catcomplete({
minLength: 2,
source:'search_suggestions.php'
});
});
</script>
Finally this is the actual input field on the page:
<input class="u-full-width" placeholder="Search" id="searchInput" />
Sorry if this is too much code!
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);
});