Simple Horizontal Bar Graph using php

后端 未结 3 1969
鱼传尺愫
鱼传尺愫 2021-01-01 08:11

I have seen a facebook application in which clicking on a radio button renders a graph.

As you can see below:

I wanted to know whether t

3条回答
  •  庸人自扰
    2021-01-01 08:41

    You can do it with just CSS by setting the background-position of an background image of a span.

    Let's say that the maximum width of the bar is 200 pixels. The HTML and CSS for this bar might look something like this:

    Sweaters with leggings
    

    And CSS:

    span.bar {
        background: url(bar_bg.png) 0 0 repeat-y;
        display: block;
        width: 200px;
        line-height: 20px;
    }
    

    Notice the background image? For that, you need a 400px * 1px sized image, where the leftmost 200 pixels is colored with the color you want the bars to be, the rest being white or transparent. If you set this background to the span with background position of 0 0, the bar will be 100% colored, and if you put background position of -200px 0, the bar will be blank. So, you'll just have to determine where to set your background position among these extremes for each of your values.

    First you have to find the maximum of the values you want to represent. The maximum value has an background position of 0 0, whereas value of 0 has background position of -200px 0.

    The PHP code to calculate and apply the background position goes like this:

    $values = array(
                49 => 'Sweaters with leggings',
                37 => 'Scarves with everything',
                14 => 'Cute knit hats and gloves');
    
    // Find the maximum percentage
    $max = max(array_keys($values));
    
    foreach($values as $percentage => $label) {
        // Calculate the position, maximum value gets position 0, smaller values approach 200
        $pos = 200 - ($percentage / $max) * 200;
        // Output the label that shows the percentage
        echo '';
        // Output the span, apply style rule for the background position
        echo ''.$label.'';
    }
    

    If you want to use different coloured bar for the highest value as in your example, you can just do another background image and apply a class to the span with the highest value:

    echo ''.$value.'';
    

    And in CSS:

    span.bar.bar_max {
        background: url(bar_max_bg.png) 0 0 repeat-y;
    }
    

    And that's it, no need for extra DIV's or external libraries, just two simple background images. If you're handy, you can even combine the two images into one. Please let me know if this is helpful, and also if I didn't explain something clear enough.

提交回复
热议问题