Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

15.9. Program: Generating Bar Charts from Poll Results

When displaying the results of a poll, it can be more effective to generate a colorful bar chart instead of just printing the results as text. The function shown in Example 15-4 uses GD to create an image that displays the cumulative responses to a poll question.

Example 15-4. Graphical bar charts

function pc_bar_chart($question, $answers) { // define colors to draw the bars $colors = array(array(255,102,0), array(0,153,0), array(51,51,204), array(255,0,51), array(255,255,0), array(102,255,255), array(153,0,204)); $total = array_sum($answers['votes']); // define some spacing values and other magic numbers $padding = 5; $line_width = 20; $scale = $line_width * 7.5; $bar_height = 10; $x = $y = $padding; // allocate a large palette for drawing, since we don't know // the image length ahead of time $image = ImageCreate(150, 500); $bg_color = ImageColorAllocate($image, 224, 224, 224); $black = ImageColorAllocate($image, 0, 0, 0); // print the question $wrapped = explode("\n", wordwrap($question, $line_width)); foreach ($wrapped as $line) { ImageString($image, 3, $x, $y , $line, $black); $y += 12; } $y += $padding; // print the answers for ($i = 0; $i < count($answers['answer']); $i++) { // format percentage $percent = sprintf('%1.1f', 100*$answers['votes'][$i]/$total); $bar = sprintf('%d', $scale*$answers['votes'][$i]/$total); // grab color $c = $i % count($colors); // handle cases with more bars than colors $text_color = ImageColorAllocate($image, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata