Core PHP

Labeled 2D Pie Chart with GD

This GD example program demonstrates the code for an example program that demonstrates how to draw a labeled 2D pie chart with GD and create a png image.

LabeledPieChart2D.php

<?php
  function DrawPieChart2D($iImageWidth, $iImageHeight, $dacData, $sGraphLabel) {
    $qFont = './verdana.ttf';
    $qImage = imagecreate($iImageWidth, $iImageHeight);
    $iGraphWidth = $iImageWidth - 80;
    $iGraphHeight = $iImageHeight - 50;
    $iCenterX = round($iGraphWidth/2) + 10;
    $iCenterY = round($iGraphHeight/2) + 10;
    $dTotal = array_sum($dacData);
    $dInitialAngle = 0;
    // Fill in the background
    $qBackgroundColor = imagecolorallocate($qImage, 235, 245, 220);
    imagefilledrectangle($qImage, 0, 0, $iImageWidth, $iImageHeight, $qBackgroundColor);
    $dLegendDeltaY = 2;
    $qTextColor = imagecolorallocate($qImage, 32, 32, 32);
    foreach($dacData as $qLabel=>$qValue) {
      $dFinalAngle  = ($qValue/$dTotal) * 360 + $dInitialAngle;
      $qCurrColor   = imagecolorallocate($qImage, 60 + rand(0, 127), 60 + rand(0, 127),
        60 + rand(0, 127));
      imagefilledarc($qImage, $iCenterX, $iCenterY, $iGraphWidth, $iGraphHeight,
        $dInitialAngle, $dFinalAngle, $qCurrColor, IMG_ARC_PIE);
      $dVectorX = $iCenterX + (cos(deg2rad(($dInitialAngle+$dFinalAngle)/2))*($iGraphWidth/4));
      $dVectorY = $iCenterY + (sin(deg2rad(($dInitialAngle+$dFinalAngle)/2))*($iGraphHeight/4));
      $dInitialAngle = $dFinalAngle;
      imagettftext($qImage, 10, 0, $dVectorX, $dVectorY, $qTextColor, $qFont, $qValue);
      // Legend
      imagefilledrectangle($qImage, $iGraphWidth+8, $dLegendDeltaY, $iGraphWidth+26,
        $dLegendDeltaY+20, $qCurrColor);
      imagettftext($qImage, 12, 0, $iGraphWidth+30, $dLegendDeltaY + 16, $qTextColor, $qFont,
        $qLabel);
      $dLegendDeltaY += 26;
    }
    imagettftext($qImage, 10, 0, $iImageWidth/2 - 220, $iImageHeight - 10, $qTextColor, $qFont,
      $sGraphLabel);
    imagearc($qImage, $iCenterX, $iCenterY, $iGraphWidth, $iGraphHeight, 0, 360, $qBackgroundColor);
    return $qImage;
  }

  $dacData = array(1999=>850, 2003=>1096, 2007=>1508, 2011=>1770);
  $qPieChartImage = DrawPieChart2D(600, 500, $dacData,
    "United States Homeschool Students in 1000s for Given Years");

  header('Content-type: image/png');
  imagepng($qPieChartImage);
  imagedestroy($qPieChartImage);
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.