TQ
dev.com

Blog about software development

Subscribe

Vertical bar graph in HTML+CSS

09 Jun 2016 - by 'Maurits van der Schee'

I wanted to display a simple bar graph, but as you know this site does not use JavaScript nor cross domain requests. I came up with the following PHP function to make a vertical bar graph using only HTML and CSS to render the graph:

function vertical_bar_graph($values,$height,$title='',$description='') {
    $real_max = max($values);
    $max = pow(10,ceil(log10($real_max)));
    while ($max/2>$real_max) $max/=2;
    $html = '<div>';
    $html.= '<div style="position: relative; clear: both; text-align: center;">';
    $html.= $title.'</div>';
    for ($i=0;$i<10;$i++) {
        if ($i%2==0) {
            $html.= '<div style="position: relative; top: '.($i/10*$height).'px; width: 100%;">';
            $html.= '<div style="position: absolute; width: 100%; text-align: left; border-top: 1px solid #aaa;">';
            $html.= '&nbsp;'.((1-$i/10)*$max);
            $html.= '</div>';
            $html.= '<div style="position: absolute; width: 100%; text-align: right; border-top: 1px solid #aaa;">';
            $html.= ((1-$i/10)*$max).'&nbsp;';
            $html.= '</div>';
            $html.= '</div>';
        } else {
            $html.= '<div style="position: relative; top: '.($i/10*$height).'px; width: 100%;">';
            $html.= '<div style="position: absolute; width: 100%; text-align: left; border-top: 1px solid #ccc;">';
            $html.= '</div>';
            $html.= '</div>';
        }
    }
    $c = count($values);
    foreach ($values as $key=>$value) {
            $p = round(100*($value/$max));
            $title = is_string($key)?$key.': '.$value:$value;
            $html.= '<div style="float: right; width: '.(100/$c).'%; height: '.$height.'px;">';
            $html.= '<div style="width: 100%; height: 100%; background-color: #eee;">';
            $html.= '<a style="display: block; position: relative; margin: 0 10%; background-color: #aaa; height: '.$p.'%; top: '.(100-$p).'%" title="'.$title.'">';
            $html.= '</a>';
            $html.= '</div>';
            $html.= '</div>';
    }
    $html.= '<div style="position: relative; clear:both; border-top: 1px solid #aaa;">';
    $html.= $description.'</div>';
    $html.= '</div>';
    return $html;
}
echo vertical_bar_graph($values,300,'Traffic TQdev.com','Unique visitors (y-axis) per day (x-axis)')

The output of this graph is:

Traffic TQdev.com
 2500
2500 
 2000
2000 
 1500
1500 
 1000
1000 
 500
500 
Unique visitors (y-axis) per day (x-axis)

As you can see the graph renders nicely over the full width of the container and is smart enough to determine the y-axis values by itself. It is also responsive and works fine on a smaller screen. Just give the function a list of values and a height in pixels to render the graph at (and optionally a title and a description).


PS: Liked this article? Please share it on Facebook, Twitter or LinkedIn.