Monday, March 3, 2014

PHP Simple Bar Chart

A simple bar chart using php



index.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
//----------class----------
class graph{
public function setHeight($h = 300){
return $h;
}
public function setWidth($w = 500){
return $w;
}
public function setBar($h = 150, $w = 30){
return $h.','.$w;
}
}
//-------------------------
$graph = new graph;
$width = $graph->setWidth();
$height = $graph->setHeight();
echo '<div id="graph" style="width:'.$width.'px;height:'.$height.'px">';
$data['A'] = 150;
$data['B'] = 20;
$data['C'] = 50;
$data['D'] = 25;
$data['E'] = 98;
$data['F'] = 167;
$i=0;
foreach($data as $label => $value){
$i++;
$barsize = explode(',',$graph->setBar($value,40));
$mtop = ($height - $barsize[0]) - 1;
$mleft = 6+($barsize[1]+8)*$i;
echo '<div id="bar" style="height:'.$barsize[0].'px;width:'.$barsize[1].'px;margin:'.$mtop.'px 0 0 '.$mleft.'px;" onMouseOver=getBarLabel('.$i.',1) 
onMouseOut=getBarLabel('.$i.',0)>'.$value.'</div>
<div id="label'.$i.'" style="margin:'.($mtop+10).'px 0 0 '.($mleft-10).'px;background:#FFF;display:none;width:100px;padding:0 0 0 5px;z-index:1">'.$label.'</div>';
}
echo '</div>';
?>
</body>
<script type="text/javascript">
function getBarLabel(i,e){
var label = document.getElementById("label"+i);
if(label){
if(e==1)
label.style.display="";
else
label.style.display="none";
}
}
</script>
</html>

style.css
#graph {
border-bottom-width: 1px;
border-left-width: 1px;
border-bottom-style: solid;
border-left-style: solid;
border-bottom-color: #060;
border-left-color: #090;
vertical-align: bottom;
margin-top: 50px;
margin-left: 50px;
}
#graph div {
border: 1px solid #039;
position: absolute;
background-color: #36F;
}

No comments:

Post a Comment