1

I had to implement bar chart for my school surveys project and I think I almost finished but nothing can be perfect and here's my question. I implemented this code http://www.rgraph.net/docs/bar.html via this tutorial http://www.rgraph.net/docs/integration-with-server-side-scripting.html#mysql but I have one problem. I need to paint bar of graph depend on it's height, for example values equal to 3 are green, less than 1.5 are red. Code i use looks like this

print('<script src="../libraries/RGraph.bar.js"></script>' . "\n\n");
print('<canvas id="cvs1" width="600" height="200">[No canvas support]</canvas>' . "\n\n");
print('<script>' . "\n");
print('window.onload = function (){'."\n\n");
print('var bar = new RGraph.Bar('.cvs1.', ['.$data_string.'])' . "\n\n");
print('.Set(\'labels\',[\'1\',\'2\',\'3\',\'4\',\'5\',\'6\',\'7\',\'8\',\'9\',\'10\',\'11\',\'12\',\'13\',\'14\'])'. "\n\n");
print(' .Set(\'colors\', [\'Gradient(#94f776:#50B332:#B1E59F)\', \'Gradient(#94f776:#50B332:#B1E59F)\', \'Gradient(#f2a011:#f2a011:#f2a011:#f2a011)\'])'. "\n\n");
print('.Set(\'hmargin\', 15)'. "\n\n");
print('.Set(\'strokestyle\', \'white\')'. "\n\n");
print('.Set(\'linewidth\', 1)'. "\n\n");
print('.Set(\'shadow\', true)'. "\n\n");
print('.Set(\'shadow.color\', \'#ccc\')'. "\n\n");
print('.Set(\'shadow.offsetx\', 0)'. "\n\n");
print('.Set(\'shadow.offsety\', 0)'. "\n\n");
print('.Set(\'shadow.blur\', 10)'. "\n\n");
print('.Set(\'ymax\', 5)'. "\n\n");
print('.Set(\'colors.sequential\', true)'. "\n\n");
print('.Draw();'. "\n\n");
print('}'. "\n\n");
print('</script>'. "\n\n");

Where this one print('var bar = new RGraph.Bar('.cvs1.', ['.$data_string.'])' . "\n\n"); is code that get data from database. I have tried to write simple php for and even foreach loop to print colours but it didn't work. Code looked like this

foreach($data_string as $param)
if ($param<1){
    return(' .Set(\'colors\', [\'Gradient(#FF0000:#FF0000:#FF0000)\'])'. "\n\n");
}
else if($param<=2){
    return(' .Set(\'colors\', [\'Gradient(#f2a011:#f2a011:#f2a011:#f2a011)\'])'. "\n\n");
}
else
    return(' .Set(\'colors\', [\'Gradient(#94f776:#50B332:#B1E59F)\'])'. "\n\n");
}

I am sure the code that prepare data for foreach loop is good because i use it to display colours of data in HTML table. Is there any solution

1 Answers1

0

PHP:

<?php
    $colors = array();

    foreach($data_string as $param) {
        if ($param < 1) {
            $colors[] = 'red';
        }

        if ($param > 3) {
            $colors[] = 'green';
        }
    }

    $colors_str = implode(', ', $colors);
?>

JavaScript

obj.Set('colors', [ <?php echo $colors_str; ?> ]);

PS. If you switch into HTML mode you won't need to do so much escaping of quotes in your PHP code. Or span strings across multiple lines - and use quotes carefully. Like so:

PHP:

<?php
    print("obj.Set('colors', ['red', green', 'blue'])\n\n");
?>
Richard
  • 4,809
  • 3
  • 27
  • 46